How to get Scope Identity Column while inserting datatable using stored procedure

后端 未结 1 1948
野趣味
野趣味 2021-01-27 18:48

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

相关标签:
1条回答
  • 2021-01-27 19:33

    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;
    
    0 讨论(0)
提交回复
热议问题