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
我需要的答案是-1
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
我需要的答案是-1
我将从分别显示每个步骤的详细方法开始。
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
(ie 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
您应该将日期作为日期类型进行比较:
只需执行(此处为小提琴演示):
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