MSSQL loop (Vernier loop and For-like loop)
Use cursor loops:
DECLARE My_Cursor CURSOR-- define cursor FOR (SELECT * FROM dbo.Table)-- find the collection you need and put it in the cursor OPEN My_Cursor;-- Open the cursor FETCH NEXT FROM My_Cursor;-- read the first row of data WHILE @ @ FETCH_STATUS = 0 BEGIN-- UPDATE dbo.Table SET field 1 ='* * 'WHERE CURRENT OF My_Cursor;-- Update-- DELETE FROM dbo.Table WHERE CURRENT OF My_Cursor -- Delete FETCH NEXT FROM My_Cursor;-- read the next row of data ENDCLOSE My_Cursor;-- close the cursor DEALLOCATE My_Cursor;-- release the cursor
Use the cursor assignment loop:
Declare @ Parameter1 Parameter1 Type, @ Parameter2 Parameter2 Type DECLARE MyCursor CURSOR-define cursors (using cursor loops) FOR (select field 1, field 2 from Table)-find the collection needed and put order by field 1-sort statement outside parentheses OPEN MyCursor;-Open cursor FETCH NEXT FROM MyCursor INTO @ Parameter1, @ Parameter2 -- read the first line of data WHILE @ @ FETCH_STATUS = 0Begin if condition holds begin-- if you want to skip the current loop, you need to assign a value first, and then continue, otherwise you will enter the endless loop FETCH NEXT FROM MyCursor INTO @ parameter 1, @ parameter 2; continue -- Skip the current loop, enter the next loop end if condition to set begin Break;-- jump out of the entire loop end / * the * /-- PRINT @ parameter 1 and parameter 2 that need to be processed in the loop -- print parameter values (debug)-- UPDATE Table set field 3 parameters, field 4 parameters * where field 1 parameters @ parameter 1 and field 2 parameters @ parameter 2-- Insert into Table1 (field 1 Field 2) values (parameter 1, parameter 2)-- Delete from table where field 1 = parameter 1 and field 2 = parameter 2 FETCH NEXT FROM MyCursor INTO @ parameter 1, @ parameter 2 -- enter the next loop EndCLOSE MyCursor; after assignment-- close the cursor DEALLOCATE MyCursor;-- release the cursor
A SQL loop similar to a For loop:
Declare @ itemnumber int-defines the number of times a loop is required declare @ tagint int-defines a flag field that ends the loop set @ tagint=1 select @ itemnumber = count (distinct Creater) from Demo_TestTable where isnull (Creater,'')''And DATEDIFF (DAY,CreatDate,GETDATE ()) 0) begin while @ tagint