sql - 有没有办法在不使用 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 语句中注入)
解决方案
您不嵌套CTE,但它们可以是以下内容的一部分insert
:
with cte as (
. . .
)
insert into . . .
select . . .
from cte;
您可以在insert
.
请注意,在大多数数据库中,CTE 是 的一部分select
,因此您可以为所欲为。
推荐阅读
- c# - 用于在表中存储日期的字符串由于未知原因正在转换 int
- java - 通过单击摆动来处理父窗口的热点
- linux - chmod 744 到我的主目录,同一组中的其他用户仍然无法复制/cd 我的文件
- python - Python:将变量的数据移动到配置ini
- javascript - Angular-oauth-oidc,调用 OAuthService.silentRefresh() 时 AuthConfig 为空
- vue.js - 无法在 vue.js 组件中捕获滚动事件
- laravel - 如何在 Laravel 中获取模型关系?
- mysql - 操作数应在 Mysql 中包含 1 列 - 错误 #1241
- zapier - 字段“id”应该是最新任务中的整数:Zapier
- animation - 如何检查 AnimatedContainer 是否完全动画?