How to get Scope Identity Column while inserting d

2020-05-07 05:42发布

问题:

I'm inserting datatable using stored procedure and created a type table before, the query is i want to get back all the 'ProdID' that has been inserted in this session. for the single insertion i can get the scope identity but i want to get all for the recent insertion.

Thanks in advance.

[dbo].[sp_Isert] (@dt_Product Product_Table READONLY, @ProdID int out)  
AS
INSERT into tblProduct (Name,Batch,Qty,ExpDate)
SELECT Name, Batch, Qty, ExpDate
FROM  @dt_Product;

set @ProdID = Scope_Identity( )

select Scope_Identity( ) ProdID

回答1:

Do not use scope_identity() - use the output clause instead. Note that SQL Server does not support table valued parameters as out parameters, meaning the only way to return a record set from a stored procedure is either by using the output clause (not into table) or by executing a select statement.

Also, do not use the sp prefix for stored procedured.
Microsoft is using this prefix for system procedues, so you might get a name collision.

ALTER PROCEDURE [dbo].[stp_Isert] (@dt_Product Product_Table READONLY)  
AS

INSERT into tblProduct (Name,Batch,Qty,ExpDate)
OUTPUT Inserted.Id -- This will return a recordset with the inserted ids to the calling application.
SELECT Name, Batch, Qty, ExpDate
FROM  @dt_Product;

Update

I've made a sample script for you to check. When I'm running this on my SQL Server instance, I get the expected results:

CREATE TABLE tbl_TestOutputClause (Id int identity(1,1), Col int );
GO
CREATE TYPE udt_TestOutputClauseIntegers AS TABLE (Value int);
GO

CREATE PROCEDURE stp_TestOutputClauseInsert (@Values dbo.udt_TestOutputClauseIntegers READONLY)
AS
    INSERT INTO tbl_TestOutputClause(Col)
    OUTPUT INSERTED.Id
    SELECT Value
    FROM @Values;

GO

CREATE PROCEDURE stp_TestOutputClauseGetInsertedValues 
AS
    DECLARE @Ids AS TABLE (Id int);
    DECLARE @Vals dbo.udt_TestOutputClauseIntegers;
    INSERT INTO @Vals (Value) VALUES (1), (2), (3);

    INSERT INTO @Ids
    EXEC stp_TestOutputClauseInsert @Vals;

    -- should return three rows with the values 1, 2 and 3.    
    SELECT *
    FROM @Ids;

GO

EXEC stp_TestOutputClauseGetInsertedValues;

-- clean up
DROP TABLE tbl_TestOutputClause;
DROP PROCEDURE stp_TestOutputClauseInsert;
DROP PROCEDURE stp_TestOutputClauseGetInsertedValues 
DROP TYPE udt_TestOutputClauseIntegers;