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

前端 未结 9 1290
陌清茗
陌清茗 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()
    
    0 讨论(0)
  • 2020-12-02 18:38
    insert into Yourtable()  
    values()  
    SELECT SCOPE_IDENTITY()
    

    I just ran a test and verified that the semi-colons are optional using SQL Server 2005 SP2, and .Net 3.5

    0 讨论(0)
  • 2020-12-02 18:38

    Straight out of the Whirlpool:

    If you're using MS SQL you can use "SELECT @@IDENTITY as Value" after your insert to get the last ID generated

    and:

    @@IDENTITY and SCOPE_IDENTITY return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

    Edit: As pointed out in the comments, you should always use SCOPE_IDENTITY, not @@IDENTITY.

    0 讨论(0)
  • 2020-12-02 18:49
    INSERT INTO YourTable(val1, val2, val3 ...) 
    VALUES(@val1, @val2, @val3...);
    SELECT SCOPE_IDENTITY();
    

    Don't forget the semicolons at the end of each statement.

    0 讨论(0)
  • 2020-12-02 18:50

    Immediately after your insert stmt, use

    SELECT CAST(scope_identity() AS bigint) ---- incase you have a return result as int64
    

    This will return the column created id/identity.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题