I have a table with users and I pull out all the ID in this way:
SELECT UserID FROM Users
Now for each ID from this list I need to do certain operations (with other tables using these IDs)
Tell me how to organize a cycle in SQL
I have a table with users and I pull out all the ID in this way:
SELECT UserID FROM Users
Now for each ID from this list I need to do certain operations (with other tables using these IDs)
Tell me how to organize a cycle in SQL
It is not necessary to dwell on cursors - there is still the good old while
(for clarity, an example for the case when the UserId field is the primary key):
declare @id int = 0 while exists(select 1 from Users where UserId >= @id) begin select top(1) @id = UserId from Users where UserId >= @id -- необходимые операции set @id = @id + 1 end
Try using the cursor
I think you need connections . And cycles are a procedural approach that should be avoided whenever possible.
If you can’t do without a cycle at all, you can use the cursor:
DECLARE @UserID int DECLARE user_cursor CURSOR FOR SELECT UserID FROM Users OPEN user_cursor FETCH NEXT FROM user_cursor INTO @UserID WHILE @@FETCH_STATUS = 0 BEGIN -- сделать что-то с текущим @UserID FETCH NEXT FROM user_cursor INTO @UserID END CLOSE user_cursor; DEALLOCATE user_cursor;
Source: https://ru.stackoverflow.com/questions/250910/
All Articles