Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get inserted ID in SQL Server while using SqlClient class?

So this is a continuation of post: Best way to get identity of inserted row?

That post proposes, and I agree, to use Inserted feature to safely return inserted id column(s).

While implementing this feature, it seems SqlClient of the .net framework does not support this feature, and fails while trying to execute command, I get the following exception:

System.Data.SqlClient.SqlException: 'Cannot find either column "INSERTED" or the user-defined function or aggregate "INSERTED.Id", or the name is ambiguous.'

I'm just using:

return (T)command.ExecuteScalar();

Where the query is:

INSERT INTO MyTable 
OUTPUT INSERTED.Id 
(Description) 
VALUES (@Description)

And the table just contains

ID (identity int)
Description (varchar(max))

If impossible to do, is there other safe way without using variables in the middle that might affect performance?

Thanks

like image 573
Yogurtu Avatar asked Apr 12 '18 01:04

Yogurtu


People also ask

How can I get identity value after inserting SQL Server?

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.

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.


1 Answers

You are doing everything correctly, but you have misplaced the OUTPUT clause: it goes after the list of columns and before the VALUES, i.e.

INSERT INTO MyTable (Description) 
OUTPUT INSERTED.Id 
VALUES (@Description)
like image 110
Sergey Kalinichenko Avatar answered Sep 21 '22 11:09

Sergey Kalinichenko