2010-07-01 58 views
0

在我之前的問題中,我問過將查詢的結果存儲在變量中......現在我意識到查詢可以返回多行。我可以將存儲過程查詢中的多行傳入另一個查詢嗎?

目前,我有這樣的:

SELECT @UserId = UserId FROM aspnet_Users WHERE UserName = @username 

我想要做這樣的事情:

DELETE FROM some_table WHERE UserId IN (*the ID list*) 
DELETE FROM some_table_2 WHERE UserId IN (*the ID list*) 

我的第一反應就是用「GROUP_CONCAT」,但顯然這是一個MySQL特有的功能。有一些方法可以使等價的功能,但我想知道是否有更好的方式來構建查詢?

+0

@OMG小馬:爲什麼要刪除'group-concat'標籤?這不重要,但重點是什麼? – DisgruntledGoat 2010-07-01 18:09:54

回答

4
SELECT * FROM dbo.aspnet_UsersInRoles 
WHERE UserId IN ( 
    SELECT UserId FROM aspnet_Users 
    WHERE UserName = @username 
) 
+0

雖然我想使用相同的ID執行多個查詢。對每個人使用子查詢會有點混亂。 – DisgruntledGoat 2010-07-01 18:15:31

+0

從一點研究看來,如果我多次使用相同的查詢,結果將被緩存。仍然讓我的代碼看起來有點亂,但是無論如何。 – DisgruntledGoat 2010-07-22 10:06:53

1

這應該做到這一點..

SELECT 
    * 
FROM 
    dbo.aspnet_UsersInRoles 
WHERE 
    UserId IN ( 
      SELECT 
       UserId 
      FROM 
       aspnet_Users 
      WHERE 
       UserName = @username 
     ) 
0
delete from st 
    from some_table st 
     inner join aspnet_Users au 
      on st.UserId = au.UserId 
    where /* add additional criteria here to produce "* the ID list *" */ 
0

如果你想避免重複子查詢,你可以把它的結果到一個臨時表或表變量。例如:

/*declare and fill a table variable containing all user ids you need to manipulate*/ 
declare @t table(userid int) 
insert into @t(userid) select UserId from aspnet_Users where [email protected] 

/*delete from some table by using the temp variable*/ 
delete from st 
from some_table st 
    inner join @t t 
     on st.userid = t.userid 
/*repeat this for some other table*/ 
delete from st 
from some_other_table st 
    inner join @t t 
     on st.userid = t.userid 

如果你想避免多次delete語句,如果在some_other_table用戶ID的存在,如果這並不在some_table存在沒有意義,那麼你可以在some_table創建觸發器:

create trigger x on some_table for delete 
    as 
    begin 
    delete from some_other_table 
    where userid in (select userid from deleted) 
    end 
相關問題