Declare @time1 datetime;
Declare @time2 datetime;
right(@time1,7) = 9:00 Am
right(@time2,7) = 3:10 Pm
case when @time1 > @time2 then 1 else -1 end as small
我要求的ans是-1
答案 0 :(得分:0)
我将从详细显示每个步骤的详细方法开始。
DECLARE @time1 datetime;
SET @time1 = Current_Timestamp;
DECLARE @time2 datetime;
SET @time2 = DateAdd(hh, -29, @time1);
; WITH dateparts AS (
SELECT @time1 As time1
, DatePart(hh, @time1) As hh1
, DatePart(mi, @time1) As mi1
, DatePart(ss, @time1) As ss1
, DatePart(ms, @time1) As ms1
, @time2 As time2
, DatePart(hh, @time2) As hh2
, DatePart(mi, @time2) As mi2
, DatePart(ss, @time2) As ss2
, DatePart(ms, @time2) As ms2
)
, construct_time_only AS (
SELECT time1
, DateAdd(hh, hh1, DateAdd(mi, mi1, DateAdd(ss, ss1, DateAdd(ms, ms1, 0)))) As timeonly1
, time2
, DateAdd(hh, hh2, DateAdd(mi, mi2, DateAdd(ss, ss2, DateAdd(ms, ms2, 0)))) As timeonly2
FROM dateparts
)
SELECT time1
, time2
, timeonly1
, timeonly2
, CASE WHEN timeonly1 > timeonly2 THEN 1 ELSE -1 END As small
FROM construct_time_only
;
这里的想法是我们设置一个共同的基准日期进行比较。在这种情况下,我们使用1900-01-01
(即Cast(0 As datetime)
)作为我们的共同日期。
共同日期的原因是为了满足起点的日期部分不同的情况。
SQL Server 2008引入了新的date
和time
数据类型。我们可以简单Cast()
到time
并比较结果
DECLARE @time1 datetime = Current_Timestamp;
DECLARE @time2 datetime = DateAdd(hh, -1, @time1);
SELECT @time1 As time1
, Cast(@time1 As time) As timeonly1
, @time2 As time2
, Cast(@time2 As time) As timeonly2
, CASE WHEN Cast(@time1 As time) > Cast(@time2 As time) THEN 1 ELSE -1 END As small
答案 1 :(得分:0)
您应该将日期作为日期类型进行比较:
做( Fiddle demo here ):
Declare @date1 datetime = '20131017 09:00:00'
Declare @date2 datetime = '20131017 15:00:00'
--right(@time1,7) = 9:00 Am
--right(@time2,7) = 3:10 Pm
select case when @date1 > @date2 then 1 else -1 end as small
您也可以使用 Datediff() 等功能;
select case when datediff(second, @date1, @date2) > 0 then -1 else 1 end as small