SQL cursor用法例

1106 ワード


DECLARE @OldId varchar(50)  
DECLARE @CustomerID varchar(50)  
DECLARE My_Cursor CURSOR --   
FOR (select CustomerID,oldid from Customer where Area='bj') --   
OPEN My_Cursor; --   
FETCH NEXT FROM My_Cursor INTO @CustomerID,@OldId; --   
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 CustomerID=@OldId;  

      SELECT @FinalUserid=UserID from Users where oldid=@Userid  

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

     FETCH NEXT FROM My_Cursor INTO @CustomerID,@OldId; --       
    END 
CLOSE My_Cursor; --   
DEALLOCATE My_Cursor; --   
GO