c# - SPROC insert with ExecuteNonQuery and ExecuteScalar -
sql insert issue. running stored procedure insert rows table , returning id created. when run , have output parameter @id , use executenonquery() returns -1 int idinserted give me id inserted. shouldn't return 1 since record inserted. i'd use executenonquery check record inserted grab inserted id.
sql insert
@person bigint, @date datetime, @id bigint output begin set nocount on; insert table(person,date_added) values (@person,@date) select @id = scope_identity() cmd.parameters.clear(); cmd.parameters.addwithvalue("@person", person); cmd.parameters.addwithvalue("@date", datetime.now); sqlparameter output = new sqlparameter("@id", sqldbtype.int); output.direction = parameterdirection.output; cmd.parameters.add(output); int idinserted = (int)cmd.executenonquery(); if (idinserted > 0) { int id = output.value; }
when insert , c# executescalar()
sql insert @person bigint, @date datetime begin set nocount on; insert table(person ,date_added) values(@person,@date ) select scope_identity() cmd.parameters.clear(); cmd.parameters.addwithvalue("@person", person); cmd.parameters.addwithvalue("@date", datetime.now); long id = (long)cmd.executenonscalar();
executescalar()
throws following error
"specificed cast not valid
remove
set nocount on;
because removes rowcount!
Comments
Post a Comment