Translate

How to use cursor in SQL Server?

Cursor is collection of rows with a pointer that is used to identify the current row.

In different word, Cursor is a data base object that is used by an application to calculate data in a row-by-row manner, this is like a record set in the ASP.net.

Syntax with example of cursor:
DECLARE @vc_first_name varchar(50)
DECLARE @vc_last_name varchar(50)

DECLARE cur_name CURSOR /*This is Declaration of cursor*/
FOR
SELECT vc_first_name, vc_last_name FROM dbo.client

OPEN cur_name /* opening the cursor */

FETCH NEXT FROM cur_name
   INTO @vc_first_name, @vc_last_name
   PRINT @vc_first_name + ' ' + @vc_last_name /* printing the name */
WHILE @@FETCH_STATUS = 0
BEGIN
   FETCH NEXT FROM cur_name
   INTO @vc_first_name, @vc_last_name
   PRINT @vc_first_name + ' ' + @vc_last_name /* printing the name */
END

CLOSE cur_name /* closing the cursor */
DEALLOCATE cur_name /* Deallocating the cursor */

No comments:

Post a Comment