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!
WITH declares a CTE, which is something you can use in just 1 statement (like a SELECT , INSERT , UPDATE , etc.). An IF is a control flow mechanic that separates statements (or blocks of statements) so you can't declare a CTE and conditionally refer to it on multiple statements.
You can use SELECT * INTO #TempTable FROM CTE immediately after WITH CTE AS ( ) and then use IF .... ELSE .... which can column values from #TempTable for conditions in IF , ELSE.
Cannot use with CTE The clauses like ORDER BY, INTO, OPTION clause with query hints, FOR XML, FOR BROWSE, cannot be used in the CTE query definition.
Syntax. IF (a <= 20) THEN c:= c+1; END IF; If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.
Common table expressions are defined within the context of a single statement:
WITH cte_name AS ( <cte definition>) <statement that uses cte>;
So you can do something like:
WITH CTE AS ( SELECT * FROM SOMETABLE ) SELECT * FROM CTE;
or
WITH CTE AS ( SELECT * FROM SOMETABLE ) UPDATE CTE SET somefield = somevalue WHERE id = somekey;
A CTE must be followed by a single SELECT, INSERT, UPDATE, MERGE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With