TSQL - compare dates (year and calendar week) form

2019-09-01 14:19发布

问题:

I need a way to compare dates in the following string format: '2015 CW 14' or '2016 CW 03'' with the current year and week in order to test if the value is in the past or >= the current year and week.

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)) 

I believe my approach won't get me there.

回答1:

I think you have a problem on 2016 CW 03 I edit your statement to @cw2, And you can see < or > or = will work for comparing.

This clue can be useful:

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 


回答2:

I think the only safe and easy way is to compare the int values separately, as you cannot compare the strings correctly with >= without manipulation, and converting to dates is complex and redundant. The int comparison will look like this (edited):

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


回答3:

Maybe something like this:

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;