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

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?


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

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


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

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