Simple Example of Cursor in SQL Server

Here are couple of simple examples of SQL Server Cursors working for AdventureWorks database.
If you need to use cursors, adjust this simple code to fit your needs:

USE AdventureWorks;
GO
DECLARE cursor1 CURSOR FOR
SELECT BusinessEntityID, LoginID FROM HumanResources.Employee
OPEN cursor1;
FETCH NEXT FROM cursor1
WHILE @@FETCH_STATUS = 0
FETCH NEXT FROM cursor1;
CLOSE cursor1;
DEALLOCATE cursor1;
GO

cursor_sql_server_1

USE AdventureWorks
GO
DECLARE @LoginID nvarchar(256)
DECLARE @getLoginID CURSOR
SET @getLoginID = CURSOR FOR
SELECT LoginID
FROM HumanResources.Employee

OPEN @getLoginID
FETCH NEXT
FROM @getLoginID INTO @LoginID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @LoginID
FETCH NEXT
FROM @getLoginID INTO @LoginID
END
CLOSE @getLoginID
DEALLOCATE @getLoginID
GO

cursor_sql_server

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">