c# - SCOPE_IDENTITY() returns thousand number -
i have insert query below. however, scopeidentity
not return 42, returns 1042.
this sql server table:
my code:
int masterid = 0; using (sqlconnection cmd = new sqlconnection(connstring)) { using (sqlcommand conn = cmd.createcommand()) { conn.commandtext = "insert into[masterreportdata]([reportname],[caselist],[employeeid],[datetime]) values(@reportname, @caselist, @employeeid, @datetime) set @id = scope_identity()"; conn.parameters.add("@reportname", sqldbtype.varchar).value = reportname; conn.parameters.add("@caselist", sqldbtype.varchar).value = caselist; conn.parameters.add("@employeeid", sqldbtype.char).value = employeeid; conn.parameters.add("@datetime", sqldbtype.datetime).value = datetime; conn.parameters.add("@id", sqldbtype.int).direction = parameterdirection.output; cmd.open(); conn.executenonquery(); masterid = convert.toint32(conn.parameters["@id"].value); cmd.close(); } }
have @ https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql
the description says: returns last identity value inserted identity column in same scope. scope module: stored procedure, trigger, function, or batch. therefore, if 2 statements in same stored procedure, function, or batch, in same scope.
in words: returns last id , not next use. therefore can't use insert command that. can is:
configure id auto-increment id. run insert command , run select scope_identity() afterwards find out id used.
Comments
Post a Comment