Basic T-SQL cursor

For when you have to loop through a resultset using T-SQL... 
 
declare @CustId nchar(5);
declare @RowNum int;
declare CustList cursor for
   select top 5 CustomerID
from Northwind.dbo.Customers
open CustList;
fetch next from CustList 
  into @CustId;
set @RowNum = 0 
while @@FETCH_STATUS = 0
begin
    set @RowNum = @RowNum + 1;
    print cast(@RowNum as char(1)) + ' ' + @CustId;
    fetch next from CustList 
into @CustId
  end;
close CustList;
deallocate CustList;

Comments

Popular Posts