Skip to content

Instantly share code, notes, and snippets.

@eppsteve
Last active March 13, 2021 12:28
Show Gist options
  • Select an option

  • Save eppsteve/7de9aeec0ecd342a235d842120479960 to your computer and use it in GitHub Desktop.

Select an option

Save eppsteve/7de9aeec0ecd342a235d842120479960 to your computer and use it in GitHub Desktop.
T-SQL ForEach style loop
declare @Enumerator CURSOR
SET @Enumerator = CURSOR LOCAL FAST_FORWARD FOR
select UserId
from Users
where IsActive = 1
OPEN @Enumerator
declare @id int
while (1=1)
begin
FETCH NEXT FROM @Enumerator into @id
if (@@FETCH_STATUS <> 0) break
exec dbo.DoSomething @id
end
CLOSE @Enumerator
DEALLOCATE @Enumerator
declare @Enumerator table (id int)
insert into @Enumerator
select UserId
from Users
where IsActive = 1 -- your query to select a list of ids goes here
declare @id int
while exists (select 1 from @Enumerator)
begin
select top 1 @id = id from @Enumerator
exec dbo.DoSomething @id
-- your code to do something for a particular id goes here
delete from @Enumerator where id = @id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment