问题
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