What is the use of a cursor in SQL Server?

后端 未结 6 600
滥情空心
滥情空心 2020-12-13 18:47

I want to use a database cursor; first I need to understand what its use and syntax are, and in which scenario we can use this in stored procedures? Are there different synt

6条回答
  •  一向
    一向 (楼主)
    2020-12-13 19:10

    Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

    for ex:

    declare @tab table
    (
    Game varchar(15),
    Rollno varchar(15)
    )
    insert into @tab values('Cricket','R11')
    insert into @tab values('VollyBall','R12')
    
    declare @game  varchar(20)
    declare @Rollno varchar(20)
    
    declare cur2 cursor for select game,rollno from @tab 
    
    open cur2
    
    fetch next from cur2 into @game,@rollno
    
    WHILE   @@FETCH_STATUS = 0   
    begin
    
    print @game
    
    print @rollno
    
    FETCH NEXT FROM cur2 into @game,@rollno
    
    end
    
    close cur2
    
    deallocate cur2
    

提交回复
热议问题