2010-05-19 39 views
3

我需要执行该过程deleteQuestion对于被这个选择查询返回的每一个元素:执行程序元素的序列(执行theProc(从表选择ID))

select id from questions where Stuff = @Stuff 

execute deleteQuestion id 

类似:
execute deleteQuestion each(select id fom questions where Stuff = @Stuff)

有人知道如何?

+0

哪些参数是否快得多' deleteQuestions' SP拿?你必须使用'deleteQuestions' SP你可以自由地考虑替代方法吗? – 2010-05-19 08:54:51

+0

@Daniel Renshaw deleteQuestion SP将id作为参数 – Omu 2010-05-19 08:57:15

+0

游标可以用作@klausbyskov的暗示,但这样做很慢并且很麻烦。如果您可以避免使用SP,那么基于集合的语句将更加高效,并且具有SQL精​​神。 – 2010-05-19 09:02:28

回答

0

我做了这样的:

declare @sqlstr nvarchar(max) 

set @sqlstr = '' 

select @sqlstr = @sqlstr + ' exec deleteQuestion ' + cast(q.id as nvarchar(max)) 
from Questions q where stuff = @stuff 

exec (@sqlstr) 

有人告诉我,这方法比光标

5

使用cursor

DECLARE @Id INT 
DECLARE your_cursor CURSOR FOR 
SELECT id from questions where Stuff = @Stuff 

OPEN your_cursor 

FETCH NEXT FROM your_cursor 
INTO @Id 

WHILE @@FETCH_STATUS = 0 
BEGIN 

    execute deleteQuestion @Id 

    FETCH NEXT FROM your_cursor 
     INTO @Id 

END 
CLOSE your_cursor 
DEALLOCATE your_cursor