SQL 添加日期时间添加小时添加分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8020744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:09:17  来源:igfitidea点击:

SQL add Datetime add hour add Minute

sqlsql-serverdatetimeaddhour

提问by user609511

In my table I have DateTime, Hourcolumn.

在我的表我有DateTimeHour列。

example : 2012-05-14 00:00:00.000and 1230

例子:2012-05-14 00:00:00.0001230

How can I add this hourcolumn into my Datetimecolumn, so I can have

如何将此hour列添加到我的Datetime列中,以便我可以拥有

2012-05-14 12:30:00.000

I tried with this:

我试过这个:

SELECT DATE_DEBUT, HEURE_DEBUT, 
   DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 0, 2)), DATE_DEBUT) AS DateTemp, 
   DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 2, 2)), DateTemp) AS DateComplete
FROM ESPTEMPS_PROGRAMMATION

but it does not work.

但它不起作用。

thanks you in advance, Stev

提前谢谢你,史蒂夫

采纳答案by marc_s

From what I understand, you want to add the first two digits as hour, the second two as minute - but you're not doing this in your DATEADDcalls - you're adding both parts as HOUR- try this instead:

据我了解,您想将前两位数字添加为小时,将后两位添加为分钟-但您没有在DATEADD通话中这样做-您将两个部分都添加为HOUR-试试这个:

SELECT DATE_DEBUT, HEURE_DEBUT, 
   DATEADD(MINUTE, CONVERT(int, SUBSTRING(HEURE_DEBUT, 3, 2)), 
              DATEADD(HOUR, CONVERT(int, SUBSTRING(HEURE_DEBUT, 1, 2)), DATE_DEBUT))
FROM ESPTEMPS_PROGRAMMATION

Here I'm using two nested DATEADD- the inner DATEADDadds the hours, the outer adds the minutes onto the result of adding the hours.

在这里,我使用了两个嵌套DATEADD- 内部DATEADD添加小时数,外部将分钟添加到添加小时数的结果上。

Also: SUBSTRINGin SQL Server is 1-based, e.g. the first character of a string is at position 1 (not 0, as you seem to assume)

另外:SUBSTRING在 SQL Server 中是基于 1 的,例如字符串的第一个字符位于位置 1(不是 0,正如您所假设的那样)