Last active
March 13, 2021 12:28
-
-
Save eppsteve/7de9aeec0ecd342a235d842120479960 to your computer and use it in GitHub Desktop.
T-SQL ForEach style loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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