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?
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.
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.
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.
INSERT INTO YourTable(val1, val2, val3 ...) VALUES(@val1, @val2, @val3...); SELECT SCOPE_IDENTITY();
Don't forget the semicolons at the end of each statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With