Cari Blog Ini

19 Juni 2012

How To Loop Number in SQL Using Cursor

Example, want to loop number from 1 to 10

------------------------------------------------------------
-----code:start
------------------------------------------------------------
declare @CounterNum int
declare CounterNumCursor cursor for
    select 1 CounterNum

    open  CounterNumCursor
    fetch CounterNumCursor into @CounterNum
        while (@CounterNum <= 10 )
        Begin
       
            print @CounterNum
            set @CounterNum=@CounterNum+1
       
            fetch CounterNumCursor into @CounterNum
        End
   
    close CounterNumCursor
deallocate CounterNumCursor
------------------------------------------------------------
-----code:end
------------------------------------------------------------

Result Messages:
1
2
3
4
5
6
7
8
9
10