Insert NULL DateTime with SQL Server stored procedure from C#

13,605

Yes - use DBNull.Value in C#:

SqlParameter parameter = new SqlParameter("@piPurchase_Date", SqlDbType.DateTime);
parameter.Value = datePurchaseIssueDate.Checked ? datePurchaseIssueDate.Value : DBNull.Value;

to pass a NULL to a SQL Server stored procedure

Share:
13,605
Sun
Author by

Sun

Updated on June 04, 2022

Comments

  • Sun
    Sun almost 2 years

    I have written a SQL Server stored procedure that includes a DateTime parameter. This parameter could be null or contain a valid date value.

    So the definition of my variable in my procedure is below:

    @piPurchase_Date DATETIME = NULL
    

    From C# I add the parameter as follows:

    SqlParameter parameter = new SqlParameter("@piPurchase_Date", SqlDbType.DateTime);
    parameter.Value=datePurchaseIssueDate.Checked ? datePurchaseIssueDate.Value : SqlDateTime.Null;
    

    So far all seems OK but when I call the Update method on the DataAdaptor I receive the following error:

    Failed to convert parameter value from a SqlDateTime to a DateTime.

    Any ideas?

    I'm using SQL Server 2008 and C#4.0

    Thanks in advance

  • mko
    mko over 10 years
    this would generate error Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'