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

前端 未结 9 1331
陌清茗
陌清茗 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 18:37

    Add the following line to the end of the Sql Query...

    SELECT SCOPE_IDENTITY()
    

    And then use the ExecuteScalar method on the SqlCommand object...

    var rowCount = command.ExecuteScalar()
    

提交回复
热议问题