cursor

The cursor is a data buffer opened by the system for the user to store the execution result of the SQL statement

Each cursor area has a name

Users can use SQL statements to obtain records from the cursor one by one, and assign them to the main variables, and then hand them over to the main language for further processing

The main language is record-oriented, a set of main variables can only hold one record at a time

Only using host variables can not fully meet the requirements of SQL statements to output data to the application

Embedded SQL introduces the concept of cursors to coordinate these two different processing methods
The function of the cursor is actually similar to the loop, that is, you put the data in the cursor, and then use the cursor to get the data line by line.
Finally, the purpose of circularly processing data is achieved.

It is a means of looping through a set of data.

ps: The efficiency of the cursor has always been controversial. It is recommended to avoid using it when looping data with more than 1000 pieces of data.

--The following is an example
--declare variable
DECLARE @vendor_id int, @vendor_name nvarchar(50),
@message varchar(80), @product nvarchar(50)

--Declare the cursor, the result of the select will be placed in the cursor
DECLARE vendor_cursor CURSOR FOR
SELECT VendorID, Name
FROM Purchasing.Vendor
WHERE PreferredVendorStatus = 1
ORDER BY VendorID

-- open cursor
OPEN vendor_cursor

-- Take the next piece of data, because after the cursor is opened, the default pointer is in front of the first one
--The meaning of this statement is to take out the data in the first record and assign it to the previously declared variable
FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name

--If the data is fetched successfully, then...
--The while here is a loop that traverses the entire cursor
WHILE @@FETCH_STATUS = 0
BEGIN
    --This place is for writing processing procedures, here are just a few irrelevant statements
    PRINT ' '
    SELECT @message = '----- Products From Vendor: ' + @vendor_name
    PRINT @message

    --Remove the next one
    FETCH NEXT FROM vendor_cursor
    INTO @vendor_id, @vendor_name
END

--Close and release the cursor
CLOSE vendor_cursor
DEALLOCATE vendor_cursor



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326053851&siteId=291194637