Co-Authored By:

Asked by: Camila Georgius
technology and computing databasesWhich SQL command is used to iterate through each row in a cursor?
Just so, how do I run a SQL cursor?
To use cursors in SQL procedures, you need to do the following:
- Declare a cursor that defines a result set.
- Open the cursor to establish the result set.
- Fetch the data into local variables as needed from the cursor, one row at a time.
- Close the cursor when done.
Secondly, which is better cursor or while loop?
Not really. In terms of what it is doing, a while loop and a cursor both do the same thing, they operate on one row at a time. A lot of people when trying to remove cursor-based code, simply replace it with a while loop, in the hope that it will run faster, because it's not a *nasty* cursor.
In the above syntax, the declaration part contains the declaration of the cursor and the cursor variable in which the fetched data will be assigned. The cursor is created for the 'SELECT' statement that is given in the cursor declaration. In execution part, the declared cursor is opened, fetched and closed.