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

前端 未结 9 1319
陌清茗
陌清茗 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 18:51

    If your id is a Guid, then I found this solution to be best:

    INSERT INTO YourTable (val1, val2, val3) 
    OUTPUT inserted.id 
    VALUES (@val1, @val2, @val3)
    

    Thanks @Scott Ivey

    Full demo:

        internal static Guid InsertNote(Note note)
        {
                Guid id;
    
                using (
                    var connection =
                        new SqlConnection(ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString))
                {
                    connection.Open();
                    using (
                        var command =
                            new SqlCommand(
                                "INSERT INTO Notes ([Title],[Text]) " +
                                "OUTPUT inserted.id " +
                                $"VALUES ('{title}','{text}');", connection))
                    {
                        command.CommandType = CommandType.Text;
                        var reader = command.ExecuteReader();
                        reader.Read();
                        id = reader.GetGuid(reader.GetOrdinal("id"));
                    }
                    connection.Close();
                }
    
                return id;
        }
    

    I would recommend using a Stored Procedure, but this is for unit testing our repository.

提交回复
热议问题