CTEs not working when theres IF condition in the query
-
27-05-2021 - |
Question
I am trying to add functionality on my query to select which query will be executed on a certain condition.
DECLARE @Test VARCHAR(50)
SET @Test = 'A'
;WITH A AS (
Select 'A is Selected' as SELECTED),
B AS (
Select 'B is Selected' as SELECTED)
IF(@Test = 'A')
select * from A
IF(@Test <> 'A')
select * from B
As of my Sample Test code above i got:
Msg 319, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ','.
Maybe I'm missing something?
Solution
From WITH common_table_expression (Transact-SQL).
defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.
I guess you want something like this.
declare @Test varchar(50);
set @Test='A';
with A as
(
select 'A is Selected' as SELECTED
),
B as
(
select 'B is Selected' as SELECTED
)
select *
from A
where @Test = 'A'
union all
select *
from B
where @Test = 'B';
OTHER TIPS
It seems to me that you should simply put both queries inside an IF statement as follows:
IF (@Test = 'A')
select * from A
ELSE
select * from B