【发布时间】:2022-01-07 11:31:42
【问题描述】:
我想获取 CTE 查询的结果并在另一个查询中使用它。
此简化示例使用 CTE 查询返回 id 列表。
with test_cte (id,name) as (
select id, name
from test
)
select id
from test_cte
where name = 'john'
我想使用这个 id 列表来删除一些这样的记录,但是我遇到了语法错误:
delete from test
where id in (
with test_cte (id,name) as (
select id, name
from test
)
select id
from test_cte
where name = 'john'
)
有没有办法做到这一点?
【问题讨论】:
-
CTE 定义在语句的开始,而不是中间。
-
所以我不能像子查询一样使用它,对吗?
-
这不是子查询,@Madison,它是 CTE(公用表表达式):WITH common_table_expression (Transact-SQL)。 CTE 始终在语句的开始处定义,如链接文档中所示。
-
是的,我害怕那个。
-
这并不意味着你不能在 DML 语句中使用它,@Madison320,你只是用错了......
标签: sql sql-server tsql common-table-expression