Basic Cursor Example

Basic Cursor Example

These cursor basics are worth knowing even if you end up avoiding cursors in production code, since row-by-row processing is occasionally the simplest correct solution for small administrative scripts. SQL Server Cursor Basics Basic Cursor Example This is the simplest example of a SQL Server cursor. It’s the version we use most often as a […]

July 18, 2023

These cursor basics are worth knowing even if you end up avoiding cursors in production code, since row-by-row processing is occasionally the simplest correct solution for small administrative scripts.

SQL Server Cursor Basics

Basic Cursor Example

This is the simplest example of a SQL Server cursor. It’s the version we use most often as a starting point for any cursor in our T-SQL.

 

DECLARE @AccountID INT
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID
SQL Server Consulting

Need expert support for SQL Server?

Our senior database team supports SQL Server performance tuning, health checks, migrations, Remote DBA services and urgent operational issues.

Explore Services

SQL Server Consulting

Do You Need Expert Support for Your SQL Server Environment?

Aryasoft’s senior database team provides end-to-end consulting, from SQL Server performance tuning to architecture decisions.

Get SQL Server Support

4.7/5