SQLTeam.com | Weblogs | Forums

Why this IF statement does not work?

Hello

Any idea why this IF statement does not work?
DECLARE @LastDateOfLastMonth varchar = '2020-01-30'
DECLARE @LastMonthSingleDigit varchar = IF(RIGHT(RIGHT(LEFT(@LastDateOfLastMonth,7),2),1)='0',REPLACE(RIGHT(LEFT(@LastDateOfLastMonth,7),2),'0',''),RIGHT(LEFT(@LastDateOfLastMonth,7),2))

Thanks!

Please post sample data and desired final result

I am not doing a SELECT so there is no sample data involved.

I am just declaring a variable and then using an IF statement to say, if the month (from the @LastDateOfLastMonth) starts with zero, remove that zero, and if not, use the month as it is.

However, I get an error:
Msg 156, Level 15, State 1, Line 18
Incorrect syntax near the keyword 'IF'.
Msg 102, Level 15, State 1, Line 18
Incorrect syntax near ','.

Any idea?

it because you have IF it should be IIF

:rofl: :rofl: :rofl:

this sort of stuff happened to me when i started learning SQL many years ago
even to this day .. NOT ONLY you .. it happens to me a lot ... and everybody else

one type of checklist . first ..

1 Like

The code's so convoluted I'm not sure what it's doing, or why it would ever be doing it, but I think this converts the code to runnable T-SQL. Btw, there are 31 days in January.

DECLARE @LastDateOfLastMonth varchar(30) = '2020-01-30'
DECLARE @LastMonthSingleDigit varchar(30)
SET @LastMonthSingleDigit = IIF(RIGHT(RIGHT(LEFT(@LastDateOfLastMonth,7),2),1)='0',REPLACE(RIGHT(LEFT(@LastDateOfLastMonth,7),2),'0',''),RIGHT(LEFT(@LastDateOfLastMonth,7),2))
SELECT @LastMonthSingleDigit