将datetime和varchar转换为单个日期

时间:2013-10-25 11:21:47

标签: sql sql-server sql-server-2008

我有以下数据库列和值

MyDate datetimeMy_Time varchar(5)

存储的值是

2006-09-05 00:00:00.00016:47

现在我想添加这两列并获得一个datetime2006-09-05 16:47:00.000

如何在SQL中执行此操作?

更新:

某些行的DocDate和DocTime值为NULL

所以我收到的错误如Conversion failed when converting date and/or time from character string

3 个答案:

答案 0 :(得分:1)

试试这个:

select dateadd(ss, datediff(ss, 0, @My_Time), @MyDate)

关键是要明白它与......相同。

select dateadd(ss, datediff(ss, 0, cast(@My_Time as time)), @MyDate)

...但转换是明确完成的。

修改

对于默认时间和/或日期,请根据需要使用ISNULL或COALESCE。

示例:

SELECT 
  CAST(
      isnull(@date, '2000-1-1') + 
      isnull(@time, '0:0') 
    AS DATETIME)

答案 1 :(得分:1)

...简单地

DECLARE @date DATETIME
DECLARE @time VARCHAR(5)

SET @date = '2006-09-05 00:00:00.000'
SET @time = '16:47'

SELECT CAST(@date + @time AS DATETIME) -- 2006-09-05 16:47:00.000

答案 2 :(得分:0)

尝试

CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME) as CombinedDate