Return value from SQL Server Insert command using c#

76,727

Solution 1

SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.

using (var con = new SqlConnection(ConnectionString)) {
    int newID;
    var cmd = "INSERT INTO foo (column_name)VALUES (@Value);SELECT CAST(scope_identity() AS int)";
    using (var insertCommand = new SqlCommand(cmd, con)) {
        insertCommand.Parameters.AddWithValue("@Value", "bar");
        con.Open();
        newID = (int)insertCommand.ExecuteScalar();
    }
}

Solution 2

try this:

INSERT INTO foo (column_name)
OUTPUT INSERTED.column_name,column_name,...
VALUES ('bar')

OUTPUT can return a result set (among other things), see: OUTPUT Clause (Transact-SQL). Also, if you insert multiple values (INSERT SELECT) this method will return one row per inserted row, where other methods will only return info on the last row.

working example:

declare @YourTable table (YourID int identity(1,1), YourCol1 varchar(5))

INSERT INTO @YourTable (YourCol1)
OUTPUT INSERTED.YourID
VALUES ('Bar')

OUTPUT:

YourID
-----------
1

(1 row(s) affected)
Share:
76,727
Neko
Author by

Neko

Updated on July 09, 2022

Comments

  • Neko
    Neko almost 2 years

    Using C# in Visual Studio, I'm inserting a row into a table like this:

    INSERT INTO foo (column_name)
    VALUES ('bar')
    

    I want to do something like this, but I don't know the correct syntax:

    INSERT INTO foo (column_name)
    VALUES ('bar')
    RETURNING foo_id
    

    This would return the foo_id column from the newly inserted row.

    Furthermore, even if I find the correct syntax for this, I have another problem: I have SqlDataReader and SqlDataAdapter at my disposal. As far as I know, the former is for reading data, the second is for manipulating data. When inserting a row with a return statement, I am both manipulating and reading data, so I'm not sure what to use. Maybe there's something entirely different I should use for this?