Passing Null As Sqlparameter Datetime Value
I have the following query: INSERT INTO CWS_FORWARDING_PROFILE (TNR_COMPANY_PROFILE,BOL_FORWARD_MAIL,BOL_FORWARD_SMS,BOL_FORWARD_MESSAGES ,DT_MO_FROM1,DT_MO_F
Solution 1:
SqlParametermoFrom1Param=newSqlParameter("@MoFrom1", dTOForwarding.MoFrom1 == null ? DBNull.Value : dTOForwarding.MoFrom1);
moFrom1Param.IsNullable = true;
moFrom1Param.Direction = ParameterDirection.Input;
moFrom1Param.SqlDbType = SqlDbType.DateTime;
cmd.Parameters.Add(moFrom1Param);
Solution 2:
Have you tried DBNull.Value ?
SqlParameter moFrom1Param;
if (dTOForwarding.MoFrom1 != null)
moFrom1Param = new SqlParameter("@MoFrom1", dTOForwarding.MoFrom1);
else
moFrom1Param = new SqlParameter("@MoFrom1", DBNull.Value);
also, your code shows "@MoFrom1" but the error is about @ThFrom1
Solution 3:
it looks like you are not assigning the null value, something like this:
var thFrom1Param = new SqlParameter("@ThFrom1", SqlDbType.SqlDateTime);
thFrom1Param.Value = DBNull.Value;
thFrom1Param.Direction = ParameterDirection.Input;
Solution 4:
Use the null coalescing operator?? in conjuction with DBNull.Value:
SqlParameter moFrom1Param;
moFrom1Param = newSqlParameter( "@MoFrom1", dTOForwarding.MoFrom1 ?? DBNull.Value );
Solution 5:
Modifying the stored procedure works, but I think its a bit sloppy.
You can handle it in code, this work for me:
DateTime? myDate;
if (TextBoxWithDate.Text != "")
{
myDate = DateTime.Parse(TextBoxWithDate.Text);
}
else
{
myDate = null;
}
Make myDate DateTime type but nullable, if the value from the text box is null, make myDate null and send it to the stored procedure.
Post a Comment for "Passing Null As Sqlparameter Datetime Value"