c# - How I do know if SQL Server Stored Procedure that performs an Update worked? -
say have stored procedure have no control on (and no access third party db).
how know if worked?
begin update usr set usr_psswrd = @newpassword usr_usrnme = @username , usr_psswrd = @oldpassword end
i know how rows when there's select
statement in stored procedure , read rows have no idea how check if stored procedure worked or not.
this i'm doing far doesn't work. stored procedure works because password change don't know after fact.
using (sqlconnection connection = new sqlconnection(connectionstring)) { // create command , set properties. sqlcommand command = new sqlcommand(); command.connection = connection; command.commandtext = "usp_changepassword"; command.commandtype = commandtype.storedprocedure; command.parameters.add("@username", sqldbtype.varchar).value = email; command.parameters.add("@oldpassword", sqldbtype.varchar).value = oldpw; command.parameters.add("@newpassword", sqldbtype.varchar).value = newpw; try { // open connection , execute reader. connection.open(); command.executenonquery(); sqldatareader reader = command.executereader(); if (reader.hasrows) { success = true; } reader.close(); } catch (sqlexception ex) { system.diagnostics.debug.write("sqlexception error " + ex.number + ": " + ex.message); } catch (invalidoperationexception ex) { system.diagnostics.debug.write("invalid op error: " + ex.message); } catch (exception ex) { system.diagnostics.debug.write("error: " + ex.message); } { connection.close(); } }
in documentation executenonquery find
> return value > type: system.int32 > number of rows affected.
so change code
try { // open connection , execute reader. connection.open(); int rowsupdated = command.executenonquery(); if(rowsupdated > 0) { success = true; } }
this normal behavior of executenonquery
, check if stored procedure contains statements
set nocount on
if have line, executenonquery
cannot return number of rows affected , -1 return value. if cannot change stored procedure, in trouble.
the workaround comes mind user data select
query , check against inserted data (a uncomfortable situation)
Comments
Post a Comment