简体   繁体   English

查询中存在IF条件时CTE不起作用

[英]CTEs not working when theres IF condition in the query

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 消息319,第15级,州1,第5行
Incorrect syntax near the keyword 'with'. 关键字“ with”附近的语法不正确。 If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. 如果此语句是公用表表达式或xmlnamespaces子句,则前一条语句必须以分号终止。

Msg 102, Level 15, State 1, Line 8 Msg 102,第15级,状态1,第8行
Incorrect syntax near ','. ','附近的语法不正确。

Maybe I'm missing something? 也许我缺少什么?

From WITH common_table_expression (Transact-SQL) . WITH common_table_expression(Transact-SQL)开始

defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement. 在单个SELECT,INSERT,UPDATE或DELETE语句的执行范围内定义。

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';

It seems to me that you should simply put both queries inside an IF statement as follows: 在我看来,您应该将两个查询简单地放在IF语句中,如下所示:

IF (@Test = 'A')
  select * from A
ELSE
  select * from B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM