A CTE must be followed immediately by a query. Yours is not, it's followed by an IF statement.
The IF needs to go outside of the CTE.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability