首页 > 解决方案 > 有没有办法在不使用 CTE 的情况下进行递归 SQL 查询?

问题描述

我想使用从以下 CTE 获得的结果作为选择语句,以便可以将其嵌套在另一个查询中 - 据我了解,您不能使用嵌套在查询中的 CTE;

WITH cte_exp AS
(
    select
        [PrimaryKey],
        [SelfKey]
    from
        MyTable
    where PrimaryKey = 1

    UNION ALL

    select
        i.[PrimaryKey],
        i.[SelfKey]
    from
        MyTable i
        inner join cte_exp cte
            on cte.PrimaryKey = i.SelfKey
)
SELECT 'AAA' AS StandardEntry, [PrimaryKey]
FROM   cte_exp

从我的表 -

PrimaryKey | SelfKey
--------------------
     1         null
     2           1
     3         null
     4           2
     5           4
     6           3
     7           2

将产生:

StandardEntry | PrimaryKey
--------------------------
    AAA            1
    AAA            2
    AAA            4
    AAA            7
    AAA            5

但我希望能够利用此表格输出并将其插入到另一个预先存在的表中,例如:

INSERT INTO AnotherTable ([StandardEntry],[Key]) select * from  ( ... the cte as above ... ) 

我需要将其创建为存储过程还是有办法可以包装 CTE

风景不好;在 cte 之外有 PrimaryKey 选择器where PrimaryKey = 1只会导致一行而不是预期的 5 行,该变量需要在第一个 select 语句中注入)

标签: sqlsql-server

解决方案


您不嵌套CTE,但它们可以是以下内容的一部分insert

with cte as (
      . . . 
     )
insert into . . .
   select . . .
   from cte;

您可以在insert.

请注意,在大多数数据库中,CTE 是 的一部分select,因此您可以为所欲为。


推荐阅读