Extracting 'YYWW' from getdate()

  • I am trying to get a YYWW format from getdate(). I was able to do it like this

    SELECT YYWW = CASE WHEN

    LEN(CAST(DATEPART(ww,GETDATE())as VARCHAR(2))) = 2

    THEN

    CAST(RIGHT(CAST(DATEPART(yy,GETDATE())as VARCHAR(4)),2) AS CHAR(2))+CAST(DATEPART(ww,GETDATE())as VARCHAR(2))

    ELSE

    CAST(RIGHT(CAST(DATEPART(yy,GETDATE())as VARCHAR(4)),2) AS CHAR(2))+'0'+CAST(DATEPART(ww,GETDATE())as VARCHAR(2))

    END

    but I'm sure someone knows a much better way.

    Thanks in advance!!

  • That is pretty efficient as it is. There are other methods - however, what you are using is quite adequate.

    Jason...AKA CirqueDeSQLeil
    _______________________________________________
    I have given a name to my pain...MCM SQL Server, MVP
    SQL RNNR
    Posting Performance Based Questions - Gail Shaw[/url]
    Learn Extended Events

  • This version dispenses with CASE:

    SELECT YYWW = CAST( RIGHT( CAST( DATEPART(yy,GETDATE() ) as VARCHAR(4) ), 2 ) AS CHAR(2) ) +

    RIGHT( '0' + CAST( DATEPART(ww,GETDATE() ) as VARCHAR(2) ), 2 )

  • Nice. More efficient. I hadn't considered this method. Makes sense though.

    Jason...AKA CirqueDeSQLeil
    _______________________________________________
    I have given a name to my pain...MCM SQL Server, MVP
    SQL RNNR
    Posting Performance Based Questions - Gail Shaw[/url]
    Learn Extended Events

  • CirquedeSQLeil (2/8/2010)


    I hadn't considered this method. Makes sense though.

    Hi Janson,

    Is there any direct convert method to get the year and week from date time?

    I thought this code having some sense

    select convert(char(2),getdate(),12)+

    right( '0' + cast( datepart(ww,getdate() ) as varchar(2) ), 2 )

    /*or using this to get week*/

    replace(str(datepart(ww,getdate()),2,0),' ','0')

  • Excellent! Thanks so much for the help.

  • arun.sas (2/9/2010)


    CirquedeSQLeil (2/8/2010)


    I hadn't considered this method. Makes sense though.

    Hi Janson,

    Is there any direct convert method to get the year and week from date time?

    I thought this code having some sense

    select convert(char(2),getdate(),12)+

    right( '0' + cast( datepart(ww,getdate() ) as varchar(2) ), 2 )

    /*or using this to get week*/

    replace(str(datepart(ww,getdate()),2,0),' ','0')

    No direct way - you need to concatenate as you have done.

    Jason...AKA CirqueDeSQLeil
    _______________________________________________
    I have given a name to my pain...MCM SQL Server, MVP
    SQL RNNR
    Posting Performance Based Questions - Gail Shaw[/url]
    Learn Extended Events

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply