SQL cursor usage instance

Time:2022-6-16

Copy codeThe codes are as follows:
DECLARE @OldId varchar(50)  
DECLARE @CustomerID varchar(50)  
DECLARE My_ Cursor cursor — define cursor
For (select CustomerID, old from customer where area=’bj’) — find out the required set and put it in the cursor
OPEN My_ Cursor; — Open cursor
FETCH NEXT FROM My_ Cursor INTO @CustomerID,@OldId; — Read the first row of data
WHILE @@FETCH_STATUS = 0     
    BEGIN    
       DECLARE @OtherPro VARCHAR(500)  
       DECLARE @StatusID varchar(200)  
       DECLARE @Userid varchar(200)  
       DECLARE @FinalUserid varchar(200)  

      SELECT @OtherPro=OtherPro,@StatusID=CustomerStatusID,@Userid=UserID FROM bjsunmis.dbo.Customer WHERE [email protected];  

      SELECT @FinalUserid=UserID from Users where [email protected]  

      INSERT INTO CustomerotherInfo(CustomerID,OtherPro,CustomerStatusID,UserID)VALUES(@CustomerID,@OtherPro,@StatusID,@FinalUserid)  

     FETCH NEXT FROM My_ Cursor INTO @CustomerID,@OldId; — Read next row of data
    END 
CLOSE My_ Cursor; — Close cursor
DEALLOCATE My_ Cursor; — Release cursor
GO