Microsoft SQL Server

CURSOR in SQL Server

Cursor is a database object used by applications to manipulate data in a set on a row-by- row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.

In order to work with a cursor we need to perform some steps in the following order:
Declare cursor
Open cursor
Fetch row from the cursor
Process fetched row
Close cursor
Deallocate cursor

 DECLARE @UserId int -- column name    
DECLARE db_cursor CURSOR FOR
SELECT UserId FROM dbo.Users
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE dbo.Users SET name='Himen' where UserId=@UserId
FETCH NEXT FROM db_cursor INTO @UserId
END
CLOSE db_cursor
DEALLOCATE db_cursor

Leave a comment