Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come posso scorrere un recordset all'interno di una stored procedure?

Devi creare un cursore per scorrere il set di record.

Esempio di tabella:

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')

Cursore:

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

Ecco un collegamento a MSDN su come crearli.

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

Questo è il motivo per cui ho usato Raise Error invece di PRINT per l'output.
http://structuredsight.com/2014/11/24/wait-wait-dont-tell-me-on-secondo-pensiero/