.net - SqlParameter - Setting to DEFAULT Value -
how set sqlparameter's value equivalent of sql insert statement's default
keyword?
msdn documentation says "use null or not set value use default value parameter." however, doing either results in sqlexception complaining expected parameter not supplied. tried setting parameter dbnull.value results in complaint null values not being allowed.
what's correct way this?
-- table schema create table sometable (field int not null default(1)); using (var command = this.conn.createcommand()) { command.commandtext = "insert [dbo].[sometable] ([field]) values (@p0);"; var param = new sqlparameter(); param.parametername = "@p0"; //param.value = ??; command.parameters.add(param); command.executenonquery(); }
according information i've found, trick assigning null
value works, when used stored procedure parameters.
i guess want use code you've posted insert custom values table default. if so, suppose easiest way make code work call different query when value not specified:
... int? myvalue = null; // assumed use nullable int pass value method ... if (!myvalue.hasvalue) { command.commandtext = "insert [dbo].[sometable] ([field]) values (default);"; } else { command.commandtext = "insert [dbo].[sometable] ([field]) values (@p0);"; var param = new sqlparameter(); param.parametername = "@p0"; param.value = myvalue.value; param.dbtype = system.data.dbtype.int32; command.parameters.add(param); } command.executenonquery();
this should allow handle both default , non-default cases.
Comments
Post a Comment