我有一个带有日期列的简单表。我需要获取最大日期,然后今天进行比较,看看它是否早于或晚于getdate()
以下是我的表现方式。是否有更简洁的方式来表达它?
declare @maxDate datetime
declare @todayDate datetime
with firsttable as (
select max(ColumnA) as MaxColumnA from tbl
)
select @maxDate = MaxColumnA from firsttable
select @todayDate = GETDATE()
if (@maxDate > @todayDate)
begin
select 'variable date is later than today'
end
else
begin
select 'variable date is earlier than today'
end
答案 0 :(得分:6)
你不能用"如果存在"像这样?
if exists (select 1 from tbl where ColumnA > getdate()) begin
select 'variable date is later than today'
end else begin
select 'variable date is earlier than today'
end
答案 1 :(得分:1)
尝试:
select case when cast(max(date1) as date)>cast(getdate() as date)
then 'variable date is later than today' else 'variable date is earlier than
today' end from tab1
答案 2 :(得分:1)
这是另一种选择:
declare @tbl TABLE
(
Id INT PRIMARY KEY IDENTITY(1,1)
,Date DATETIME
)
INSERT INTO @tbl
(
Date
)
VALUES ('3/26/2015'),('3/26/2025')
SELECT TOP 1
CASE
WHEN Date > GETDATE() THEN 'variable date is later than today'
ELSE 'variable date is earlier than today'
END
FROM
@tbl
ORDER BY
Date DESC