Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL cursor fetch status meaning

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?

like image 226
Volkan Avatar asked Oct 07 '15 12:10

Volkan


People also ask

What is the meaning of fetch statement in SQL?

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.

When you fetch rows from a cursor How do you know there are no more rows to fetch?

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.

How we can know the status of cursor is open or not?

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.

When first fetch is executed the cursor is positioned?

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.


1 Answers

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.
like image 125
Siyual Avatar answered Sep 20 '22 23:09

Siyual