SQL Server: Concatenate Date and Time Column of Character DataType Into DateTime DataType

Suppose you have two columns of character datatype that stores date and time separately and you want to combine both of these columns and convert it to a valid datetime. You can use the following methods:

Consider these variables

Method 1 : Concatenate both strings and convert it into datetime

declare @date char(8), @time char(8)
select @date='20101001',@time ='12:10:47'
select cast(@date+' '+@time  as datetime)


In the above method both of them are combined to form a datetime and converted to datetime datatype

Concat Char Date and Time

Method 2 : Convert date value into datetime and append time part to it

declare @date char(8), @time char(8)
select @date='20101001',@time ='12:10:47'
select cast(@date as datetime)+@time


In the above method, date value is converted to datetime datatype and time value is
added to it.

Concat Char Date and Time

3 comments:

  1. We've only just got date and time separately - now you want to put them back together again?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. We've only just got date and time separately - now you want to put them back together again?

    ReplyDelete