我需要一种方法来比较以下字符串格式的日期: '2015 CW 14'
或 '2016 CW 03'
'
使用当前年份和周来测试该值是否在过去或> = 当前年份和周。
DECLARE @cw VARCHAR(50)
SET @cw = '2015 CW 13'
SELECT @cw;
SELECT Cast(Year(Getdate()) AS VARCHAR(50))
+ ' CW '
+ Cast(Datepart(week, Getdate()) AS VARCHAR(50))
我相信我的方法不会让我在那里。
答案 0 :(得分:3)
我认为您在2016 CW 03
时遇到问题我将您的对帐单修改为@cw2
,并且您可以看到<
或>
或=
将适用于比较
这条线索非常有用:
DECLARE @cw VARCHAR(50),
@cw2 VARCHAR(50)
SET @cw = '2015 CW 03'
SET @cw2 = Cast(Year(Getdate()) AS VARCHAR(50))
+ ' CW '
+ RIGHT('00' + Cast(Datepart(week, Getdate()) AS VARCHAR(50)), 2)
SELECT @cw,
@cw2,
CASE
WHEN @cw = @cw2 THEN 0
WHEN @cw < @cw2 THEN -1
ELSE 1
END
答案 1 :(得分:2)
我认为唯一安全且简单的方法是分别比较int
值,因为您无法在没有操作的情况下正确地将字符串与>=
进行比较,并且转换为日期是复杂且多余的。 int
比较将如下所示(已编辑):
declare @cw varchar(10)
set @cw = '2015 CW 17'
Select
Case
When CAST(LEFT(@cw, 4) as int) > DATEPART(yy, GETDATE())
Or ( CAST(LEFT(@cw, 4) as int) = DATEPART(yy, GETDATE())
And CAST(RIGHT(@cw, 2) as int) >= DATEPART(ww, GETDATE()) )
Then 'future'
Else 'past'
End as IntCompare
答案 2 :(得分:0)
也许是这样的:
DECLARE @cw VARCHAR(50) = '2015 CW 16';
DECLARE @d DATE = DATEADD(week, CAST(RIGHT(@cw, 2) AS INT) - 1, LEFT(@cw, 4) + '-01-01');
SELECT [Date] = @d
, [When] =
CASE
WHEN DATEPART(week, @d) - DATEPART(week, GETDATE()) = 0 AND YEAR(@d) = YEAR(GETDATE()) THEN 'Current'
WHEN DATEPART(week, @d) - DATEPART(week, GETDATE()) > 0 THEN 'Future'
ELSE 'Past'
END;