SQL IF-ELSE结构中的CTE

Meg*_*ind 5 sql-server common-table-expression

我想做这样的事情

declare @a int=1
if (@a=1)
with cte as 
(
select UserEmail from UserTable 
)
else
with cte as
(
select UserID from UserTable
)
select * from cte
Run Code Online (Sandbox Code Playgroud)

这只是一个例子,我的实际查询要复杂得多.所以我不想在CTE之后写两次SELECT声明IFELSE声明两次.

Dam*_*ver 12

如果可能的话,找到一种if完全避免声明的方法.

例如,在你的问题中这样一个简单的例子中:

;with CTE as (
      select UserEmail from UserTable where @a = 1
      union all
      select UserID from UserTable where @a != 1 or @a is null
)
select /* single select statement here */
Run Code Online (Sandbox Code Playgroud)

通常应该可以将一个或多个不同的查询组合成最终的UNION ALLcte,而不是使用if- 毕竟,组合的两个查询无论如何都必须具有兼容的结果集,以使您的原始问题有意义.


mar*_*c_s 6

你不能这样做 - CTE 必须紧跟一个可以引用它的SQL语句.您不能从使用它的语句中拆分CTE的"定义".

所以你需要这样做:

declare @a int=1

if (@a=1)
    with cte as 
    (
       select UserEmail from UserTable 
    )
    select * from cte

else

    with cte as
    (
       select UserID from UserTable
    )
    select * from cte
Run Code Online (Sandbox Code Playgroud)

您不能将CTE"定义"拆分为其用法(select * from cte)