Cari Blog Ini

19 Juni 2012

Example How To Select Each Record in SQL Using Cursor

1. Sample data
--------------------------------------------------
-----code:start
--------------------------------------------------
select * from Cabang
--------------------------------------------------
-----code:start
--------------------------------------------------

Result Messages:
KdCabang Cabang                        
-------- ------------------------------
005      BSD                          
002      JAYAKARTA                    
003      KEBON JERUK                  
004      KELAPA GADING                
007      SURABAYA                     
006      BANDUNG                      
001      PUSAT                        
008      SEMARANG                     

(8 row(s) affected)


2. Run this query to select each record

----------------------------------------------------------------
-----code:start
----------------------------------------------------------------
declare @Branch varchar(1000)
declare BranchCur cursor for
    select distinct Cabang from Cabang

    open  BranchCur
        fetch BranchCur into @Branch
        while (@@fetch_status = 0 )
        Begin
            select @Branch
       
        fetch BranchCur into @Branch
    End
close BranchCur
deallocate BranchCur
----------------------------------------------------------------
-----code:end
----------------------------------------------------------------

Result Messages:
--------------
BANDUNG                      

(1 row(s) affected)                                                                                                                             

                                                                                                                            
--------------
BSD                          

(1 row(s) affected)

--------------
JAYAKARTA                    

(1 row(s) affected)

--------------
KEBON JERUK                  

(1 row(s) affected)

--------------
KELAPA GADING                

(1 row(s) affected)

--------------
PUSAT                        

(1 row(s) affected)

--------------
SEMARANG                     

(1 row(s) affected)

--------------
SURABAYA                     

(1 row(s) affected)


Source:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926