Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from SQL Server Insert command using c#

Tags:

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?

like image 282
Neko Avatar asked Feb 16 '12 21:02

Neko


People also ask

How can get identity value after insert in SQL?

Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement. If we run any query that did not generate IDENTITY values, we get NULL value in the output. The SQL @@IDENTITY runs under the scope of the current session.

What does SQL return on insert?

An SQL INSERT statement writes new rows of data into a table. If the INSERT activity is successful, it returns the number of rows inserted into the table.

How can I get auto increment value after insert in SQL Server?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

What is ExecuteScalar in C#?

ExecuteScalar method is used to execute SQL Commands or storeprocedure, after executing return a single value from the database. It also returns the first column of the first row in the result set from a database.


1 Answers

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();     } } 
like image 123
Tim Schmelter Avatar answered Sep 25 '22 00:09

Tim Schmelter