[Solved] CONCAT leading 0 in case statement

EverSQL Database Performance Knowledge Base

CONCAT leading 0 in case statement

I found an error in a query I inherited from a previous coworker that I am trying to fix but it's a weird issue I haven't encountered before.. here is a snip of the original query:

CAST(CONCAT(DATEPART(YYYY,getdate()), 
  (CASE 
    WHEN DATEPART(WW,getdate()) < 10 
    THEN CONCAT('0', DATEPART(WW,getdate())) 
    ELSE DATEPART(WW,getdate()) 
   END)
) AS INT)

When getdate() = 2021-01-08 10:16:41.440 the query results in

20212

Expected result should be

202102

I found the issue relies in in the CASE statement. When I tried to change the THEN clause to

CAST(CONCAT(DATEPART(YYYY,getdate()), 
  (CASE 
    WHEN DATEPART(WW,getdate()) < 10 
    THEN RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2) 
    ELSE DATEPART(WW,getdate()) 
   END)
) AS INT)

I still get

20212

But when I run

SELECT RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)

I get

02

Can someone explain this? Why does it work outside of the CASE statement, but not within?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Use Numeric Column Types For Numeric Values (query line: 3): Referencing a numeric value (e.g. 0) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
The optimized query:
SELECT
        
    RIGHT('0' + CONVERT(VARCHAR(2),
    DATEPART(WW,
    getdate())),
    2)

Related Articles



* original question posted on StackOverflow here.