Question: Last night I was writing a simple T-SQL program something like this

```
DECLARE @ROLEID AS INT

SELECT @ROLEID = [ROLE ID] FROM TBLROLE

;WITH CTE
AS
( 
    SELECT * FROM SOMETABLE
)
IF (@ROLEID  = 1) 
BEGIN
      //SOMECODE
END
ELSE IF(@ROLEID  = 2) 
BEGIN
      //SOMECODE
END
ELSE
BEGIN 
      //SOMECODE
END

```

I found after compilation that it is throwing error something like "Incorrect statement near if" 

What is wrong?

However, I did that by using some other way. But I wanted to know why it did not work!

Answer: 
The closest you'll get is using a UNION ALL to do a crude switched select:

```
DECLARE @ROLEID AS INT

SELECT @ROLEID = [ROLE ID] FROM TBLROLE

;WITH CTE
AS
( 
    SELECT * FROM SOMETABLE
)
SELECT
    --somecolumns
FROM
    CTE
    --other stuff too
WHERE
    @ROLEID = 1
UNION ALL
SELECT
    --somecolumns
FROM
    CTE
    --other stuff too
WHERE
    @ROLEID = 2
UNION ALL
SELECT
    --somecolumns
FROM
    CTE
    --other stuff too
WHERE
    @ROLEID = 3
...
UNION ALL
SELECT
    --somecolumns
FROM
    CTE
    --other stuff too
WHERE
    @ROLEID = n

```
Try putting the CTE in the IF. It worked for me.

```
IF @awsome = 1
BEGIN
;WITH CTE
AS
( 
    SELECT * FROM SOMETABLE
)
    SELECT 'WHATEVERYOUWANT' FROM CTE
END
ELSE IF @awesome = 2
BEGIN
;WITH CTE2
AS
( 
    SELECT * FROM SOMETABLE
)
    SELECT 'WHATEVERYOUWANT' FROM CTE2
END

```