3

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

3
  • I think you can use String.Empty or "" and this is converted to a NULL DateTime value. Commented Jun 19, 2012 at 14:19
  • 1
    have you just tried passing in null paramter.Value = datePurchaseIssueDate.Checked ? (DateTime?) datePurchaseIssueDate.Value : null; Commented Jun 19, 2012 at 14:20
  • You might want to try replacing the null section with DbNull.Value Commented Jun 19, 2012 at 14:22

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.