【问题标题】:How to use the results of a CTE query inside another query如何在另一个查询中使用 CTE 查询的结果
【发布时间】: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


【解决方案1】:

你只是这个意思吗:

;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'
)

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

【讨论】:

  • 我必须承认,我仍然感到困惑的是,您站在将分号视为“初学者”的那一边。
  • @Larnu 因为仍会将其复制并粘贴到具有DECLARE @name varchar(32) = 'john' 的程序中,然后对我大喊我破坏了他们的代码。认为它是永久性的。
  • 那么也许你应该举一个更有代表性的例子,@Madison320。
  • @ThomasDoconski 查看评论线程。原因是人们将WITH ... 代码示例粘贴到他们现有的代码中,而之前的语句中没有分号。然后我们会因为给他们糟糕的代码而受到指责。您可以在语句之前和之后使用任意数量的分号,因此除了必须解释自己之外,将自己与前面隔离开来并没有危害。我开始怀疑哪个更糟。
  • 在这种情况下@AaronBertrand 有一个非常有效的观点:您问错了问题,即您过于简单化了,因此您的问题的最佳答案在您的现实世界用例中不起作用......跨度>
猜你喜欢
  • 1970-01-01
  • 2016-04-06
  • 2011-12-02
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多