Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a cursor in SQL Server?

I want to use a database cursor; first I need to understand what its use and syntax are, and in which scenario we can use this in stored procedures? Are there different syntaxes for different versions of SQL Server?

When is it necessary to use?

like image 686
Red Swan Avatar asked Nov 19 '10 07:11

Red Swan


People also ask

What is the use of cursor in database?

Cursors are used by database programmers to process individual rows returned by database system queries. Cursors enable manipulation of whole result sets at once. In this scenario, a cursor enables the sequential processing of rows in a result set.

When would you use a cursor?

Use of Cursor The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike the SQL commands which operate on all the rows in the result set at one time. Cursors are used when the user needs to update records in a singleton fashion or in a row by row manner, in a database table.

Is it good to use cursor in SQL?

SQL Cursors are fine as long as you use the correct options: INSENSITIVE will make a temporary copy of your result set (saving you from having to do this yourself for your pseudo-cursor). READ_ONLY will make sure no locks are held on the underlying result set.


1 Answers

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

like image 121
Jeffrey Hantin Avatar answered Sep 22 '22 15:09

Jeffrey Hantin