I don't understand the meaning of following lines:
WHILE 1 = 1
BEGIN
FETCH NEXT FROM SomeCursor INTO @SomeId, @SomeOtherColumn
IF @@FETCH_STATUS <> 0 BREAK
What are the meanings of while 1=1? and if fetch status is different than 0?
The FETCH statement retrieves rows of data from the result set of a multiple-row query—one row at a time, several rows at a time, or all rows at once—and stores the data in variables, records, or collections.
If @@FETCH_STATUS is <> 0 (-1 or -2) then it points that there are no more rows that can be returned from the cursor and you have reached its end.
You can use the CURSOR_STATUS function to determine its state. For anyone else trying this with a cursor you yourself opened, and is maybe is left allocated because of error handling, you may have to change the global part to local . Curse of the infamous SO copy/paste :-P.
The cursor is positioned on the row or rowset that is specified by the orientation clause (for example, NEXT ROWSET), and those rows are fetched if a target is specified. After the cursor is positioned on the first row being fetched, the next k-1 rows are fetched.
This is a trick that is commonly used to avoid writing the FETCH NEXT
line twice in the code. It starts an endless loop via WHILE 1 = 1
and continues until the @@FETCH_STATUS
returns something other than 0, indicating that it has either reached the end of the cursor, or an error has occurred.
The possible @@FETCH_STATUS
values are:
Return value Description
0 The FETCH statement was successful.
-1 The FETCH statement failed or the row was beyond the result set.
-2 The row fetched is missing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With