100 Days of SQL

sql

Day 84 – Cursors

These are database objects that allow you to traverse through the result set of a query one row at a time. Cursors can be useful when you need to perform complex processing on each row of a result set.

DECLARE @CustomerID INT
DECLARE @CustomerName VARCHAR(50)

DECLARE customer_cursor CURSOR FOR
SELECT CustomerID, CustomerName FROM Customers

OPEN customer_cursor

FETCH NEXT FROM customer_cursor INTO @CustomerID, @CustomerName

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Customer ID: ' + CAST(@CustomerID AS VARCHAR(10)) + ', Name: ' + @CustomerName
    FETCH NEXT FROM customer_cursor INTO @CustomerID, @CustomerName
END

CLOSE customer_cursor
DEALLOCATE customer_cursor

In this example, a cursor named customer_cursor is used to retrieve the CustomerID and CustomerName from the Customers table. The cursor is then used in a loop to print out the ID and name of each customer.