gpt4 book ai didi

sql-server - SQL IF-ELSE 结构中的 CTE

转载 作者:行者123 更新时间:2023-12-02 11:24:36 27 4
gpt4 key购买 nike

我想做这样的事情

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

这只是示例,我的实际查询要复杂得多。所以我不想写 SELECT内部声明 IFELSE在 CTE 之后声明两次。

最佳答案

如果可能,想办法避免 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 */

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

关于sql-server - SQL IF-ELSE 结构中的 CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com