如何在sql server 2008中减去两个时间值。我在存储过程中使用时间变量。
请帮助
答案 0 :(得分:24)
您可以使用DATEDIFF()
:
SELECT DATEDIFF(Day, startDate, endDate)
FROM table
SELECT DATEDIFF(Second, date, GETDATE())
FROM table
答案 1 :(得分:4)
DECLARE @END TIME = '16:00:00.0000000' ,
@START TIME = '01:00:00.0000000'
SELECT convert(TIME,dateadd(ms,DateDiff(ss, @START, @END )*1000,0),114)
答案 2 :(得分:2)
以下表达式适用于我
declare @starttime Time, @endtime Time
set @starttime='18:45'
set @endtime='22:45'
select DATEDIFF(HH,@starttime, @endtime)
输出:4
答案 3 :(得分:0)
即使您使用的是偏移值或正常日期,此代码也会为您提供适当的答案。
BEGIN TRY
DECLARE @OffSetVal1 VARCHAR(39) = '2019-12-02 09:15:29 +14:00'
, @OffSetVal2 VARCHAR(39) = '2019-12-02 09:15:29 +12:30'
, @minutes INT = 0
, @OffSetDiff VARCHAR(19) = ''
, @HourDiff INT = 0
SET @HourDiff = DATEDIFF(HOUR,@OffSetVal1,@OffSetVal2) -- To Check digits of hours.
SET @minutes = DATEDIFF(MINUTE,@OffSetVal1,@OffSetVal2) -- To Convert minutes to hours.
SET @OffSetDiff = @minutes / 60 + (@minutes % 60) / 100.0 -- To Check '+' Or '-' And To Get Value.
SELECT CASE WHEN CAST(@OffSetDiff AS FLOAT) <= 0
THEN (CASE WHEN @HourDiff < 10
THEN FORMAT(CAST(@OffSetDiff AS FLOAT),'0#.00')
ELSE FORMAT(CAST(@OffSetDiff AS FLOAT),'0#.00')
END)
ELSE (CASE WHEN @HourDiff < 10
THEN '+'+FORMAT(CAST(@OffSetDiff AS FLOAT),'0#.00')
ELSE '+'+FORMAT(CAST(@OffSetDiff AS FLOAT),'0#.00')
END)
END
END TRY
BEGIN CATCH
PRINT N'It seems you provided an invalid DateTimeOffSet Parameter. '
END CATCH
ANS:-+01.30(#时差与分钟和分钟的偏差,如果您不希望'+'只需从代码中删除然后运行代码)