Search code examples
sqlsql-servert-sqlsql-server-2014

Formatting with SQL DATEPART


I am using DATEPART(WEEK,mydate) to return the week number of my date, but when the week is only single number i.e. at the beginning of the year I want to format it as 01 instead of 1.

I am using SQL Server 2014, I have tried using the option format(datepart(week,mydate),'ww') but am just getting ww as my answer which as you can tell isn't quite right


Solution

  • You can use FORMAT with d2

    SELECT FORMAT(datepart(week,'2017-01-05'), 'd2')
    -- RETURN 01
    
    SELECT FORMAT(datepart(week,GETDATE()), 'd2')
    -- RETURN 23