Using SQL Server 2008, this query works great:
select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field
Gives me two co
This works in SQL 2008 and 2012 to produce datetime2:
declare @date date = current_timestamp;
declare @time time = current_timestamp;
select
@date as date
,@time as time
,cast(@date as datetime) + cast(@time as datetime) as datetime
,cast(@time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,@date) - 1,dateadd(year,datepart(year,@date) - 1900,cast(@time as datetime2))) as datetime2;
Cast it to datetime
instead:
select CAST(CollectionDate as DATETIME) + CAST(CollectionTime as TIME)
from field
This works on SQL Server 2008 R2.
If for some reason you wanted to make sure the first part doesn't have a time component, first cast the field to date, then back to datetime
.
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), date, 112) + ' ' + CONVERT(CHAR(8), time, 108))
FROM tablename
DECLARE @ADate Date, @ATime Time, @ADateTime Datetime
SELECT @ADate = '2010-02-20', @ATime = '18:53:00.0000000'
SET @ADateTime = CAST (
CONVERT(Varchar(10), @ADate, 112) + ' ' +
CONVERT(Varchar(8), @ATime) AS DateTime)
SELECT @ADateTime [A nice datetime :)]
This will render you a valid result.
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate
and CollectionTime
to char sequences, combine them, and then convert them to a datetime
.
The parameters to CONVERT
are data_type
, expression
and the optional style
(see syntax documentation).
The date and time style value 112
converts to an ISO yyyymmdd
format. The style
value 108
converts to hh:mi:ss
format. Evidently both are 8 characters long which is why the data_type
is CHAR(8)
for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss
and then converted to a datetime
.
I am using SQL Server 2016 and both myDate
and myTime
fields are strings. The below tsql statement worked in concatenating them into datetime
select cast((myDate + ' ' + myTime) as datetime) from myTable