asp.net - Trying to get SELECT SCOPE_IDENTITY() as c# variable -
i inserting row 1 table want new id can add in variable have email address stored.
var db = database.open("mydb"); var insertcommand1 = "insert mydb (firstname, lastname) values(@0, @1)"; db.execute(insertcommand1, first, last); var lastinsertedid = db.queryvalue("select scope_identity()"); var insertcommand2 = "insert email (id_person, email) values(@0, @1)"; db.execute(insertcommand2, lastinsertid, email);
where id_person id created in first table. when run code lastinsertedid = {}. reason why not grabbing value id_person primary key, int , not null first table? --tim
from the documentation of scope_identity(), emphasis mine:
returns last identity value inserted identity column in same scope. scope module: stored procedure, trigger, function, or batch. therefore, 2 statements in same scope if in same stored procedure, function, or batch.
because using 2 queries considered 2 batches. need insert , select in single query.
i don't know library using, guessing on syntax beleive need like
var db = database.open("mydb"); var insertcommand1 = "insert mydb (firstname, lastname) values(@0, @1); " + "select scope_identity()"; var lastinsertedid = db.queryvalue(insertcommand1, first, last); var insertcommand2 = "insert email (id_person, email) values(@0, @1)"; db.execute(insertcommand2, lastinsertid, email);
Comments
Post a Comment