执行一系列元素的过程(执行theProc(从表中选择id))

时间:2010-05-19 08:51:15

标签: sql sql-server

我需要为此select查询返回的每个元素执行过程deleteQuestion

select id from questions where Stuff = @Stuff

execute deleteQuestion id

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

有谁知道怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

我被告知这种方法比光标快得多