Perform the procedure for a sequence of elements (execute theProc (select id from the table))

I need to execute a procedure deleteQuestionfor each element that was returned by this select request:

select id from questions where Stuff = @Stuff

execute deleteQuestion id

sort of:
 execute deleteQuestion each(select id fom questions where Stuff = @Stuff)

Does anyone know how?

+3
source share
2 answers

I did it like this:

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)

I was told that this approach is much faster than the cursor

0
source

Use 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
+5
source

Source: https://habr.com/ru/post/1746142/


All Articles