In: Computer Science
SQL Assignment
Discuss why and when cursors could be used.
Answer-
Definition-
In SQL cursor is a control structure that enables the traversal
over the records in a database. SQL controls context area through a
cursor. Cursors facilitate subsequent processing in conjunction
with traversal, such as removal, addition and retrieval of database
records. The database cursor characteristic of traversal makes
cursors akin to programming language concept of iterator.
Two types of cursors are as follows −
Implicit cursors
Explicit cursors
Why and when Cursors are Used-
The reason why we need to use a cursor is that you need to perform actions on individual rows.Using a cursor, we can iterate or move from one row to the next and updating rows as we go. If we encounter an error, try something else, or skip operation. The difference is, that when you use cursors, you can act on each of the row.
In SQL, operations are made on a set of rows.Lets take an example, a SELECT statement returns a set of rows which is called a result set. Sometimes application logic needs to work with one row at a time rather than for entire result set at once. This can be done using the cursors.
In the programming, we use a loop like FOR or WHILE to iterate through one item at a time, the cursor follows the same approach and might be preferred because it follows the same logic.