如何在另一个查询中使用 CTE 查询的结果

How to use the results of a CTE query inside another query

我想获取 CTE 查询的结果并在另一个查询中使用它。

此简化示例使用 CTE 查询 return 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'
)

有办法吗?

你是不是这个意思:

;with test_cte(id,name) as
(
  select id,name from dbo.test
)
delete test_cte where name='john';

是否要删除行并且显示您删除的行?

;with test_cte(id,name) as
(
  select id,name from dbo.test
)
delete test_cte 
output deleted.id, deleted.name
where name='john';

以您的明确示例为例:

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 必须预先定义,而不是在查询中的任何随机或任意点。

;with test_cte (id,name) as (
    select id, name
    from test
)
delete from test
where id in (
    select id
    from test_cte
    where name = 'john'
)

但与我展示的更简单的示例相比,这似乎仍然过于复杂。