In an extract I am dealing with, I have 2 datetime
columns. One column stores the dates and another the times as shown.
How can I query the table to combine these two fields into 1 column of type datetime
?
Dates
2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000
Times
1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000
SELECT CAST(CAST(@DateField As Date) As DateTime) + CAST(CAST(@TimeField As Time) As DateTime)
If you're not using SQL Server 2008 (i.e. you only have a DateTime data type), you can use the following (admittedly rough and ready) TSQL to achieve what you want:
It's rough and ready, but it works!
This is an alternative solution without any char conversions:
You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.
If the time element of your date column and the date element of your time column are both zero then Lieven's answer is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated:
You can simply add the two.
Time part
of yourDate
column is always zeroDate part
of yourTime
column is also always zero (base date: January 1, 1900)Adding them returns the correct result.
Rationale (kudos to ErikE/dnolan)
Edit regarding new SQL Server 2008 types
Date
andTime
are types introduced inSQL Server 2008
. If you insist on adding, you can useCombined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)
Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith)
Have a look at How to combine date and time to datetime2 in SQL Server? to prevent loss of precision using SQL Server 2008 and up.
If both of your fields are datetime then simply adding those will work.
eg:
If you used Date & Time datatype then just cast the time to datetime
eg: