Thursday, June 19, 2014

jamming a CASE statement into a WHERE clause in MSSQL

This caused an error:

WHERE p.CompanyId=c.CompanyId
AND (CASE WHEN @Location = 13 THEN p.StateId = 42 ELSE p.StateId =
      p.StateId END)

 
 

This didn't cause an error, but the ELSE scenario ended up returning no records. I don't know why. It seems to me like it should have worked.

WHERE p.CompanyId=c.CompanyId
AND p.StateId = (CASE WHEN @Location = 13 THEN 42 ELSE p.StateId END)

 
 

This is the porridge Goldilocks picked:

WHERE p.CompanyId=c.CompanyId
AND 42 = (CASE WHEN @Location = 13 THEN p.StateId ELSE 42 END)

No comments:

Post a Comment