Trying to get SELECT SCOPE_IDENTITY() as c# variable

断了今生、忘了曾经 提交于 2020-03-03 07:47:07

问题


I am inserting a row into one table then want to get that new ID so I can add it in another variable where I have email address stored.

 var db = Database.Open("myDB");
 var insertCommand1 = "INSERT INTO myDB (FirstName, LastName) Values(@0, @1)";                       
 db.Execute(insertCommand1, first, last);
 var lastInsertedId = db.QueryValue("SELECT SCOPE_IDENTITY()");

 var insertCommand2 = "INSERT INTO email (id_person, email) Values(@0, @1)";
 db.Execute(insertCommand2, lastInsertId, email);

where id_person is the id that is created in my first table. When I run the code I get lastInsertedId = {}. Any reason why it is not grabbing a value for id_person which is a primary key, int , not null for my first table? --Tim


回答1:


From the documentation of SCOPE_IDENTITY(), emphasis mine:

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

Because you are using two queries they are considered two batches. You need to do your insert and your select in a single query.

I don't know what library you are using, so I am just guessing on the syntax but I beleive you need something like

 var db = Database.Open("myDB");
 var insertCommand1 = "INSERT INTO myDB (FirstName, LastName) Values(@0, @1); " +
                      "SELECT SCOPE_IDENTITY()";
 var lastInsertedId = db.QueryValue(insertCommand1, first, last);

 var insertCommand2 = "INSERT INTO email (id_person, email) Values(@0, @1)";
 db.Execute(insertCommand2, lastInsertId, email);



回答2:


If the database is in SQL SERVER , create a SQL parameter and set the direction to "Output". Please check this link :

Getting the identity of the most recently added record



来源:https://stackoverflow.com/questions/39111849/trying-to-get-select-scope-identity-as-c-sharp-variable

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