Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sql

sql-server

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 use the ExecuteScalar() method?

like image 817
Mats Avatar asked Dec 01 '08 12:12

Mats


People also ask

How can I return ID after INSERT in SQL Server?

We use SCOPE_IDENTITY() function to return the last IDENTITY value in a table under the current scope. A scope can be a module, trigger, function or a stored procedure. We can consider SQL SCOPE_IDENTITY() function similar to the @@IDENTITY function, but it is limited to a specific scope.

How do I get the inserted record ID in Linq?

after inserting the record into database it returns your record with created Id. You don't need to call any other method to get the id, you already got that after successful insertion so check your object which you passed in you "InsertOnSubmit" method. Here Customers is your table name.

How do you retrieve the last identity value that is generated?

In SQL Server, you can use the T-SQL @@IDENTITY system function to return the last-inserted identity value in the current session. Note that it returns the last identity value generated in any table in the current session.


1 Answers

INSERT INTO YourTable(val1, val2, val3 ...)  VALUES(@val1, @val2, @val3...); SELECT SCOPE_IDENTITY(); 

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

like image 171
Dave Markle Avatar answered Sep 28 '22 13:09

Dave Markle