Passing a boolean type into a bit parameter type in C# and MS SQL Server -
i have c# method accepts clientid (int) , haspaid (boolean) represents if client has paid or not. ms sql server stored procedure expects bit value (1 or 0) @haspaid parameter yet method expects boolean
type (true/false) haspaid. ado.net code take care of converting boolean
bit
type sql server or need convert value of haspaid
1 or 0
?
public void updateclient(int clientid, bool haspaid) { using (sqlconnection conn = new sqlconnection(this.myconnectionstring)) { using (sqlcommand sqlcommand = new sqlcommand("uspupdatepaymentstatus", conn)) { sqlcommand.commandtype = commandtype.storedprocedure; sqlcommand.parameters.addwithvalue("@clientid", clientid); sqlcommand.parameters.addwithvalue("@haspaid", haspaid); sqlcommand.connection.open(); var rowsaffected = sqlcommand.executenonquery(); } } }
when working sql parameters find addwithvalue
's auto detection feature of type unreliable. find better call add
explicitly set type, add
returns new parameter creates function call can call .value
on afterward.
public void updateclient(int clientid, bool haspaid) { using (sqlconnection conn = new sqlconnection(this.myconnectionstring)) { using (sqlcommand sqlcommand = new sqlcommand("uspupdatepaymentstatus", conn)) { sqlcommand.commandtype = commandtype.storedprocedure; sqlcommand.parameters.add("@clientid", sqldbtype.int).value = clientid; sqlcommand.parameters.add("@haspaid", sqldbtype.bit).value = haspaid; sqlcommand.connection.open(); var rowsaffected = sqlcommand.executenonquery(); } } }
using correct type doubly important when using stored procedures , expecting specific type, got in habit of doing way.
Comments
Post a Comment