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


Question

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?

1
48
12/1/2008 1:39:31 PM

Accepted Answer

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

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

74
3/20/2012 10:34:49 PM

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()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon