c# - optional parameters in stored procedure -
i building website using mvc , want save data using stored procedure contains set of parameters. wondering if it's possible set of parameters optional. reason being data gets sent depends on type of account. if user edits account type 1, parameters must sent back, if edit account type 2, 3 parameters sent back.
sql parameters:
alter procedure web.maint_updateclinic @accountid int ,@isactive bit = 1 ,@accountname varchar(100) = null ,@accountaddress varchar(100) = null ,@city varchar(100) = null ,@state varchar(2) = null ,@zipcode varchar(10) = null ,@phonenumber varchar(20) = null ,@webid int
action in controller calling procedure:
using (odbcconnection _conn = new odbcconnection("filedsn=c:\\datasources\\rxcard.dsn")) using (odbccommand cmd1 = new odbccommand()) { cmd1.connection = _conn; cmd1.commandtext = "{call web.maint_updateclinic(?,?,?,?,?,?,?,?,?)}"; cmd1.parameters.addwithvalue("@accountid", accountid); cmd1.parameters.addwithvalue("@isactive", true); cmd1.parameters.addwithvalue("@accountname", accountname); cmd1.parameters.addwithvalue("@address", address); cmd1.parameters.addwithvalue("@city", city); cmd1.parameters.addwithvalue("@state", state); cmd1.parameters.addwithvalue("@zipcode", zipcode); cmd1.parameters.addwithvalue("@phonenumber", phonenumber); cmd1.parameters.addwithvalue("@webid", cookiestore.getcookie("webid")); cmd1.commandtype = commandtype.storedprocedure; _conn.open(); cmd1.executenonquery(); _conn.close(); }
if parameters optional in stored procedure can choose whether add them. example, if remove line (above)
cmd1.parameters.addwithvalue("@accountname", accountname);
then stored procedure use default value of @accountname
.
that means need way determine whether or not pass each parameter. how tougher answer because depends on behavior of application.
you could, example, this:
if(accountname != null) cmd1.parameters.addwithvalue("@accountname", accountname);
in other words, if value wasn't provided accountname
don't send 1 procedure. works long don't need able set accountname
null
using method.
you pass parameter method indicating account type is, , use determine parameters add , leave out.
i noticed have separate variables each value (account
, address
, etc.) might easier work if put them class, like
public class clinicupdate { public string accountid {get;set;} public string address {get;set;} //etc }
that can make lot easier if decide rearrange code. example, might decide make 2 methods - 1 adds parameters 1 type of account, , add parameters other type. that's lot easier if you're passing around single object instead of big list of parameters.
it's practice anyway. opinions vary recommend maximum of 4 parameters per method call. if find passing similar list of parameters many methods need class them.
Comments
Post a Comment