Red*_*ght 2 sql-server-2008 t-sql datetime
我正在尝试编写一个存储过程来确定两次之间的秒数差异。如果我要对我知道可以使用的值进行硬编码
CAST(datediff(second, [start], [end])/3600.0 As Decimal(18,4)))
Run Code Online (Sandbox Code Playgroud)
但我只需要在满足条件的情况下才能获得差异。我的想法是做这样的事情
Declare @diff decimal(18,4)
Create Table #Dope
(
date1 datetime
,inlate decimal(16,4)
)
INSERT INTO #Dope (date1) Values
('2016-01-04 08:08:47.000'),
('2016-01-04 08:25:59.000'),
('2016-01-04 08:27:47.000'),
('2016-01-04 08:00:00.000')
if CAST(date1 As Time) > '08:00:00.000'
--Here is where the capture would come but I am unsure of how to type it
SET @diff = CAST(datediff(second, [], [date1])/3600.0 As Decimal(18,4))
Run Code Online (Sandbox Code Playgroud)
如何将 Set 语句中的第一个日期时间设置为我需要秒差的当天上午 8 点?意思是,我不能只是将 '08:00:00.000' 硬编码到我的 Set 语句中,因为这两个日期我是不同的,这会给我跨越几天的秒数,这不是我所追求的。我只想看看 date1 和 '08:00:00.000' 之间的秒数差异
首先,我不确定你为什么要除以 3600 .. 那将返回 1/3600 秒。
其次,你有点想多了。尝试这个:
CREATE TABLE #NotDope
(
date1 datetime
)
INSERT INTO #NotDope (date1) Values
('2016-01-04 08:08:47.000'),
('2016-01-04 08:25:59.000'),
('2016-01-04 08:27:47.000'),
('2016-01-04 08:00:00.000'),
('2016-01-04 07:55:00.000')
SELECT date1,
CASE WHEN CAST(date1 AS Time) > '08:00:00.000' THEN
datediff(second, '08:00:00', CAST([date1] AS time))
ELSE 0 END AS SecondsLate
FROM #NotDope
Run Code Online (Sandbox Code Playgroud)
您需要做的就是将日期转换为时间数据类型以去除日期部分。