I have a table with users and I pull out all the ids from there:
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 on SQL
Answer 1, Authority 100%
not necessarily looped on the cursors – there is still an old-kind while
(for clarity, an example for the case when the user’s primary key field):
declare @id int = 0
While Exists (Select 1 From Users WHERE UserID & GT; = @ID)
Begin.
SELECT TOP (1) @ID = UserID From Users WHERE UserID & GT; = @ID
- Necessary operations
SET @ID = @ID + 1
End.
Answer 2
Try to use cursor
Answer 3
I think you need connections .
And cycles are a procedural approach to which it should be avoided.
Answer 4
If without a cycle, you can not do 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.
- do something with current @userid
Fetch Next From User_Cursor
Into @userid
End.
Close user_cursor;
Deallocate user_cursor;