我正在尝试在查询中添加功能,以选择在特定条件下执行哪个查询。
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
从上面的示例测试代码开始,我得到了:
Msg 319,Level 15,State 1,Line 5
关键字'with'附近的语法不正确。如果此语句是公用表表达式或xmlnamespaces子句,则必须以分号结束前一个语句。Msg 102,Level 15,State 1,Line 8
附近的语法不正确
','。
也许我错过了什么?
答案 0 :(得分:4)
来自WITH common_table_expression (Transact-SQL)。
在单个SELECT,INSERT,UPDATE的执行范围内定义, 或DELETE语句。
我想你想要这样的东西。
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';
答案 1 :(得分:1)
在我看来,你应该简单地将两个查询放在IF语句中,如下所示:
IF (@Test = 'A')
select * from A
ELSE
select * from B