SQL 语句中未使用的 CTE 会是 运行

Will unused CTE in a SQL statement be run

我有一个关于 CTE 的问题。您可以通过 WITH 开始一个 sql 语句,然后您可以构建一个或多个 CTE 查询,然后您最终可以在 select on.

上创建(在本例中)

我的问题是:是会执行所有 CTE 查询还是只执行正在使用的查询?

例如

WITH cte_1
as (
 Select * from table1
),
cte_2
as (
 Select * from table2
)
Select * from cte_1

这是否意味着 select 将在 table1 和 table2 上执行?

我收到这条消息:

Msg 422 Level 16 State 4 Line 2

Common table expression defined but not used.

当 运行:

with cte as (select 1/0 as val)
select 1

Here 是一个 db<>fiddle.

完成戈登大师的回答(我敢):

如果您声明 2 个 cte,并使用其中 none 个,您也会收到该错误消息

with cte as (select 1/0 as val), cte2 as (select 1/0 as val)
select 1

Msg 422 Level 16 State 4 Line 2 
Common table expression defined but not used.

但如果您至少使用一个,则接受该声明:

with cte_divide_by_zero as (select 1/0 as val), cte_legit as (select 'it works' as val)
select * from cte_divide_by_zero 

Msg 8134 Level 16 State 1 Line 1
Divide by zero error encountered.

如果您 select 另一个 CTE,则证明您未使用的 CTE 从未执行过,因为没有发生错误:

with cte_divide_by_zero as (select 1/0 as val), cte_legit as (select 'it works' as val)
select * from cte_legit 

val
--------
it works