Transact SQL – While fetch example

Often a good example is worth more than 1000 words.
Here’s how to run, on Sql Server, one for each / while in Transact Sql.

DECLARE @Id INT
DECLARE @Name NVARCHAR(50)
DECLARE @LastName NVARCHAR(50)

DECLARE MY_CURSOR CURSOR FOR 
SELECT Id, Name, LastName FROM Users WHERE Salary > 10000

OPEN MY_CURSOR 

FETCH NEXT FROM MY_CURSOR INTO @Id, @Name, @LastName

WHILE @@FETCH_STATUS = 0 
BEGIN 
	
    PRINT CONCAT('ID: ', @Id, ' NAME: ', @Name, ' LASTNAME: ', @LastName)
    
    FETCH NEXT FROM MY_CURSOR INTO @Id, @Name, @LastName

END 

CLOSE MY_CURSOR 
DEALLOCATE MY_CURSOR

Leave a Comment

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