How can I iterate over a recordset within a stored procedure?

后端 未结 3 657
醉梦人生
醉梦人生 2021-02-02 12:33

I need to iterate over a recordset from a stored procedure and execute another stored procedure using each fields as arguments. I can\'t complete this iteration in the code. I h

3条回答
  •  孤街浪徒
    2021-02-02 12:57

    You need to create a cursor to loop through the record set.

    Example Table:

    CREATE TABLE Customers
    (
        CustomerId INT NOT NULL PRIMARY KEY IDENTITY(1,1)
        ,FirstName Varchar(50) 
        ,LastName VARCHAR(40)
    )
    
    INSERT INTO Customers VALUES('jane', 'doe')
    INSERT INTO Customers VALUES('bob', 'smith')
    

    Cursor:

    DECLARE @CustomerId INT, @FirstName VARCHAR(30), @LastName VARCHAR(50)
    
    DECLARE @MessageOutput VARCHAR(100)
    
    DECLARE Customer_Cursor CURSOR FOR 
        SELECT CustomerId, FirstName, LastName FROM Customers
    
    
    OPEN Customer_Cursor 
    
    FETCH NEXT FROM Customer_Cursor INTO
        @CustomerId, @FirstName, @LastName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @MessageOutput = @FirstName + ' ' + @LastName
    
    
    
        RAISERROR(@MessageOutput,0,1) WITH NOWAIT
    
        FETCH NEXT FROM Customer_Cursor INTO
        @CustomerId, @FirstName, @LastName
    END
    CLOSE Customer_Cursor
    DEALLOCATE Customer_Cursor
    

    Here is a link to MSDN on how to create them.

    http://msdn.microsoft.com/en-us/library/ms180169.aspx

    This is why I used Raise Error instead of PRINT for output.
    http://structuredsight.com/2014/11/24/wait-wait-dont-tell-me-on-second-thought/

提交回复
热议问题