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

前端 未结 9 1336
陌清茗
陌清茗 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条回答
  •  孤街浪徒
    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());
    

提交回复
热议问题