SQL DateTime Data Types

DataTimechart

In this demonstration we will see how to work with the various datetime data types within in SQL Server. Prior to SQL Server 2008 we only had the DATETIME and SMALLDATETIME data types. Now we have four additional data types to help be more efficient in storing our data. We will start with an example of the DATETIME data type.

DATETIMEexample

In this example we declare a variable of the DATETIME data type and then set the value to February 16, 2012 at 1:30pm. Notice that the date and time is surround with single quotes as if it is literal text. This is because SQL Server does not know how to tell the difference between dates and actual math. For example let’s try a different format for the date to see what happens.

baddatetime

How did we get June 15, 1894? This is because a DATETIME will begin at 1/1/1900. When SQL Server tries to translate the 02-16-2012 it thought we were adding and subtracting days. So, first it added 2 days, then subtracted 16 days, then subtracted 2012 days.

So to tell SQL Server that this is a date value and not actual math we use single quotes around the date and time. SQL Server will see it first as a character data type that needs to be implicitly converted to one of the date or time data types.

Now with the DATETIME, DATETIME2, SMALLDATETIME, and DATETIMEOFFSET we include both date and time as part of the value. But what happens if we don’t use one part of the value.

DateTimehalfvalue

Notice that in the dtVar1 variable where we just included the date, the time defaulted to all zeros. and in the dtVar2 variable where we only included the time, the date defaulted to January 1, 1900.

Fortunately, now in SQL Server 2008 and later we have the DATE and TIME data types that will conserve space in this situation. For example, we will just the data type for dtVar1 to be the DATE data type and the dtVar2 variable to be the TIME data type.

newdatetime

Finally, be careful when going from one datetime data type to another as it is possible to truncate data that you might have wanted to keep in your database.

 

 

 

 

 

 

Be the first to comment on "SQL DateTime Data Types"

Leave a comment

Your email address will not be published.


*