100 Days of SQL

sql

Day 91 – Cursors

DECLARE @OrderID INT
DECLARE @ProductID INT
DECLARE @Quantity INT

DECLARE order_cursor CURSOR FOR
SELECT OrderID, ProductID, Quantity FROM OrderDetails

OPEN order_cursor

FETCH NEXT FROM order_cursor INTO @OrderID, @ProductID, @Quantity

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @Quantity > 10
    BEGIN
        PRINT 'Order ID: ' + CAST(@OrderID AS VARCHAR(10)) + ', Product ID: ' + CAST(@ProductID AS VARCHAR(10)) + ', Quantity: ' + CAST(@Quantity AS VARCHAR(10))
    END
    FETCH NEXT FROM order_cursor INTO @OrderID, @ProductID, @Quantity
END

CLOSE order_cursor
DEALLOCATE order_cursor

In this example, a cursor named order_cursor is used to retrieve the OrderID, `