SQL Cursors

I see SQL cursor as a loop on the table. It is highly inefficient, and can result in infinite loops if not used properly. I highly recommend trying other alternatives (like Common table Expressions – CTE’s) if it is possible.

Anyway, here is the syntax of a SQL cursor

SELECT * INTO tmpTbl FROM (SELECT 1 AS SaleID) A
TRUNCATE TABLE tmpTbl
DECLARE @saleId INT
DECLARE loop_cursor CURSOR LOCAL FOR SELECT * FROM tmpTbl
OPEN loop_cursor
FETCH NEXT FROM loop_cursor INTO @saleId
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SaleID
FETCH NEXT FROM loop_cursor INTO @saleId
END
DEALLOCATE loop_cursor

Leave a Reply

Your email address will not be published. Required fields are marked *