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

久未见 提交于 2020-01-02 07:05:13

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/49786640/how-can-i-get-inserted-id-in-sql-server-while-using-sqlclient-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!