如何在SQL中合并两个DateTime部分(小时,分钟,秒)?

时间:2015-03-05 04:54:30

标签: sql datetime

我的表中有两个日期时间字段,如下所示:

Transaction_RequestDateTime
Transaction_ResponseDateTime

我以这种方式为这个字段赋值:(在C#win form程序中)

Transaction_RequestDateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ff");
Transaction_ResponseDateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss:ff");

正如您在上面的代码中看到的,我在响应时间中使用了hh,而不是HH。所以,当我想在SQL中获得Datediff时,它不会给我正确的不同价值。

例如,值如下:

Transaction_RequestDateTime = 2015-02-13 21:28:53.390
Transaction_ResponseDateTime = 2015-02-13 09:28:54.500

正如您所看到的,区别在于Minutes,我们的第二个。 所以,我的问题是:

如何更改Transaction_ResponseDateTime值,因为小时部分就像Transaction_ResponseDateTime小时一样?

例如,我想像这样更新这两条记录:

Transaction_RequestDateTime = 2015-02-13 21:28:53.390
Transaction_ResponseDateTime = 2015-02-13 21:28:54.500 // 21 instead of 09

感谢任何帮助...

2 个答案:

答案 0 :(得分:0)

您可以使用将日期转换为varchar数据类型,然后使用左右部分。 喜欢这个

Declare @Date1 DateTime
SET @Date1 = '2015-01-01 15:45:00'

Declare @Date2 DateTime
SET @Date2 = '2015-12-31 12:00:00'

Declare @Combined DateTime

SET @Combined = Cast(Left(@Date2, 11) + Right(@Date1, 7) As DateTime)
print @Combined

您也可以像这样添加sql日期之后的时间

SET @Combined = Cast(Left(@Date2, 11) + ' 09:00:00' As DateTime)
print @Combined

<强>编辑:

如果要在SQL中获取日期对象的一部分,则可以使用DatePart函数获取日期的特定部分。例如年,月,日,小时,分钟和秒。

DatePart(expression, dateobjct)
--------------------------------

Year       : yy or yyyy
Month      : mm or m
Day        : dd or d
Weekday    : dw
Hour       : hh
Minutes    : mi or n
Seconds    : ss or s
Milli.Sec. : ms

您可以像这样使用此功能。

print DatePart(yyyy, @Date1)    
--Output will be 2015

SET @Combined = Cast(Left(@Date2, 11) + ' ' + Cast(DatePart(hh, @Date1) As Varchar) + ':00:00' As DateTime)
Select @Combined

答案 1 :(得分:0)

不确定您是否正在处理字符串,但如果这些字段作为日期时间存储在表中,那么只需计算小时数差异并将该差异添加到不正确的字段就可以了,如下所示:

CREATE TABLE Table1
    ([ID] int identity primary key, [Transaction_RequestDateTime] datetime, [Transaction_ResponseDateTime] datetime)
;

INSERT INTO Table1
    ([Transaction_RequestDateTime], [Transaction_ResponseDateTime])
VALUES
    ('2015-02-13 21:28:53', '2015-02-13 09:28:54')
;

update table1
set Transaction_ResponseDateTime =  
    dateadd(hour, 
          datepart(hour,Transaction_RequestDateTime) 
        - datepart(hour,Transaction_ResponseDateTime)
    , Transaction_ResponseDateTime)

datepart(hour,Transaction_RequestDateTime)  = 19
- datepart(hour,Transaction_ResponseDateTime) = 10

so:
dateadd(hour, (19 - 10) , Transaction_ResponseDateTime)