Skip to content

OPEN

DECLARE @CustomerCursor CURSOR
DECLARE @CustomerID int, @CustomerName nvarchar(50)
SET @CustomerCursor = CURSOR FOR
SELECT CustomerID, CustomerName FROM Customers
OPEN @CustomerCursor
FETCH NEXT FROM @CustomerCursor INTO @CustomerID, @CustomerName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CAST(@CustomerID AS varchar(11)) + ' - ' + @CustomerName
FETCH NEXT FROM @CustomerCursor INTO @CustomerID, @CustomerName
END
CLOSE @CustomerCursor
DEALLOCATE @CustomerCursor
1 - John Doe
2 - Jane Smith
3 - Robert Williams
4 - Linda Johnson

The OPEN statement in SQL is used to open a cursor, which is a database object to retrieve data from a result set one row at a time. The example packages the cursor declaration, opening, fetching data, and closing into a single transaction block. Each customer from the Customers table is printed out one at a time by their ID and name.