How to insert a record and return the newly created ID using a single SqlCommand?

前端 未结 9 1291
陌清茗
陌清茗 2020-12-02 18:18

I\'m using an SqlCommand object to insert a record into a table with an autogenerated primary key. How can I write the command text so that I get the newly created ID when I

相关标签:
9条回答
  • Although I like Dave Markle's answer, ( and I see you did too, since you marked it as your answer ), that method can fail if you have triggers on your database, that audit CUD operations, and your audit table has an IDENTITY column. It would return the value of the Audit table's identity, not the table you just inserted into, since the audit table actualy happen after.

    In that case, a more generic method can be used that will work in both cases, regardless of any auditing. Its a bit more wordy, but you get what you pay for.

    example:

    @"DECLARE @tmp AS TABLE ( id int )
                        INSERT INTO case
                        (
                            caseID,
                            partID,
                            serialNumber,
                            hardware,
                            software,
                            firmware
                        )
                        OUTPUT Inserted.ID into @tmp
                        VALUES
                        (
                            @caseID,
                            @partItemID,
                            @serialNumber,
                            @hardware,
                            @software,
                            @firmware
                        )
                    Select ID from @tmp" )
    
    0 讨论(0)
  • 2020-12-02 19:00

    Don't use @@IDENTITY, however simple it may seem. It can return incorrect values.

    SELECT SCOPE_IDENTITY()
    

    appears to be the obvious choice.

    0 讨论(0)
  • 2020-12-02 19:01

    Add an output parameter to the command object and then set the value to the new ID in the stored procedure.

    Stored Procedure:

    @ID AS INT OUTPUT
    
    [Insert Command]
    
    SET @ID = SCOPE_IDENTITY()
    

    .NET:

    cmd.CommandText = "stored_procedure";
    
    SqlParameter pID = new SqlParameter("ID", DBType.Int32, 4);
    
    pID.Direction = ParameterDirection.Output;
    
    cmd.ExecuteScalar();
    
    int id = Convert.ToInt32(cmd.Parameters["ID"].Value.ToString());
    
    0 讨论(0)
提交回复
热议问题