Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server DateTime Accept NULL

Tags:

c#

sql-server

I've tried to make my code as compact as possible.

Using Microsoft SQL Server, .NET 2.0

I have a date field in my database which accepts null values

LeaseExpiry(datetime, null)

I grab the value of the the textbox and convert it to datetime.

DateTime leaseExpiry = Convert.ToDateTime(tbLeaseExpiry.Text);

INSERT_record(leaseExpiry);

The problem I'm having is if the form is submitted and the textbox is empty. I get this error back:

String was not recognized as a valid DateTime.

How do I set my code up so that if the textbox is empty, the row is created in the database with NULL?

I've tried initializing my variable to NULL but get an error in Visual Studio

DateTime leaseExpiry = null;

Cannot convert null to 'System.DateTime' because it is a non-nullable value type.

Here's the Data Access Layer if that helps

public string INSERT_record(DateTime leaseExpiry)
{
     //Connect to the database and insert a new record 
     string cnn = ConfigurationManager.ConnectionStrings[connname].ConnectionString;

     using (SqlConnection connection = new SqlConnection(cnn))
     {
        string SQL = string.Empty;
        SQL = "INSERT INTO [" + dbname + "].[dbo].[" + tblAllProperties + "] ([LeaseExpiry]) VALUES (@leaseExpiry);

         using (SqlCommand command = new SqlCommand(SQL, connection))
         {
                command.Parameters.Add("@leaseExpiry", SqlDbType.DateTime);
                command.Parameters["@leaseExpiry"].Value = leaseExpiry;
         }

         try
         {
                connection.Open();
                command.ExecuteNonQuery();
                return "Success";
         }
         catch (Exception ex)
         {
                return ex.Message;
         }
     }
}

Thank you

like image 878
Scott Avatar asked Jan 25 '13 12:01

Scott


People also ask

Does DateTime accept NULL?

DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.

Can DateTime be NULL in SQL Server?

Using a DateTime column in an SQL table is quite common. Using it in . Net has one limitation – DateTime cannot be null as it is a struct and not a class.

How do I pass DateTime NULL in SQL?

Solution 1 DateTime datatype shouldn't be null. Instead use DateTime. Minvalue which stores the minimum value.

How do I insert a NULL into a date field in SQL?

"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);


3 Answers

Try using a nullable DateTime and TryParse()

DateTime? leaseExpirey = null;
DateTime d;
if(DateTime.TryParse(tbLeaseExpiry.Text, out d))
{
    leaseExpirey = d;
}

INSERT_record(leaseExpirey);
like image 99
Chris Gessler Avatar answered Nov 08 '22 03:11

Chris Gessler


Indeed, DateTime cannot be null. But: DateTime? can be. Note also that on a parameter, null means "don't send"; you would need:

public string INSERT_record(DateTime? leaseExpirey)
{
    // ...
    command.Parameters.Add("@leaseExpirey", SqlDbType.DateTime);
    command.Parameters["@leaseExpirey"].Value =
                ((object)leaseExpirey) ?? DBNull.Value;
    // ...
}
like image 41
Marc Gravell Avatar answered Nov 08 '22 02:11

Marc Gravell


You could make leaseExpirey a nullable DateTime - i.e. DateTime? leaseExpirey

Then you can say:

DateTime? leaseExpirey;
if (!string.IsNullOrEmpty(tbLeaseExpiry.Text.Trim()))
    leaseExpirey = Convert.ToDateTime(tbLeaseExpiry.Text);

INSERT_record(leaseExpirey);

You'd also need to change INSERT_record to accept a DateTime? parameter instead of DateTime.

like image 3
Daniel Kelley Avatar answered Nov 08 '22 03:11

Daniel Kelley