Get the App
SLTechnology News&Howtos  ›  Database  › 

How to use cursor statement in SQL Server

Shulou Source: shulou.com Published: 2022-05-31 18:58:20 10月15日 Update

This article to share with you is about how to use cursor statements in SQL Server, Xiaobian feel quite practical, so share to everyone to learn, I hope you can gain something after reading this article, not much to say, follow Xiaobian to see it.

SQL Server Cursor Statement Usage:

The code is as follows:

--Declare a cursor DECLARE MyCursor CURSOR FOR SELECT TOP 5 FBookName,FBookCoding FROM TBookInfo//Define a cursor called MyCursor to store the data after for select--Open a cursor OPEN MyCursor//i.e. open the data set--Loop a cursor DECLARE @BookName nvarchar(2000),@BookCoding nvarchar (2000) FETCH FROM MyCursor INTO @BookName,@BookCoding//Move the cursor to the first data item, Extract the first piece of data and store it in a variable WHILE @@FETCH_STATUS =0//If the previous operation succeeded, continue to loop BEGIN print 'name'+@BookName FETCH NEXT FROM MyCursor INTO @BookName,@BookCoding//Continue to lift the next line END --Close the cursor CLOSE MyCursor --Free the resource DEALLOCATE MyCursor

eg:

The code is as follows:

create table #a ( id varchar(20), name varchar(20) ) insert into #a select 1,'jack' insert into #a select 2,'join' insert into #a select 3,'make' declare mycursor cursor for select * from #a open mycursor declare @id varchar(20),@name varchar(20) fetch next from mycursor into @id,@name while @@fetch_status=0 begin select @id,@name fetch next from mycursor into @id,@name end close mycursor deallocate mycursor

The above is how to use cursor statements in SQL Server. Xiaobian believes that some knowledge points may be seen or used in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Cursors data statements code more knowledge articles loops utility success one line usage variables that is work sessions points articles methods see knowledge points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Redmi Shulou Technology OPPO Reno Microsoft