如何将两个int列转换为SQL中的time(7)值?

时间:2016-01-26 10:19:42

标签: sql-server datetime

我正在开发一个项目来更新商店连锁店的营业时间,在我收到的原始数据中,小时和分钟在2个不同的列中分隔为int值。例如:

dbo.OpeningHoursRaw

  

OpeningHour | OpeningMinute | ClosingHour | ClosingMinute
  10 | 0 | 17 |   30

我想在不同的表格中将其转换为时间(7):

dbo.OpeningHours

  

OpeningTime |   ClosingTime
  10:00:00.0000000 | 17:30:00.0000000

对于如何在MS SQL server Managment studio中使用SQL查询执行此操作,您有什么建议吗?

1 个答案:

答案 0 :(得分:1)

对于MySql,请使用MAKETIME方法:

INSERT INTO dbo.OpeningHours(OpeningTime, ClosingTime)
SELECT MAKETIME(o.OpeningHour,o.OpeningMinute,0) AS OpeningTime, MAKETIME(o.ClosingHour,o.ClosingMinute,0) AS ClosingTime
FROM dbo.OpeningHoursRaw o;

或者对于SQL Server,请使用TIMEFROMPARTS:

INSERT INTO dbo.OpeningHours(OpeningTime, ClosingTime)
SELECT TIMEFROMPARTS(o.OpeningHour,o.OpeningMinute, 0, 0, 0) AS OpeningTime, TIMEFROMPARTS(o.ClosingHour,o.ClosingMinute, 0, 0, 0) AS ClosingTime
FROM dbo.OpeningHoursRaw o;