TSQL - 比较格式为字符串的日期(年和日历周)

时间:2015-04-19 09:22:52

标签: sql-server tsql

我需要一种方法来比较以下字符串格式的日期: '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)) 

我相信我的方法不会让我在那里。

3 个答案:

答案 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;