Sql server TSQL foreach记录加入cte并插入
我需要创建一个SQL查询,它使用递归CTE从表中获取记录。(树形结构)。我把“叶子”递给他,想知道回到根的路 这适用于@SOME_ID变量Sql server TSQL foreach记录加入cte并插入,sql-server,tsql,recursion,common-table-expression,Sql Server,Tsql,Recursion,Common Table Expression,我需要创建一个SQL查询,它使用递归CTE从表中获取记录。(树形结构)。我把“叶子”递给他,想知道回到根的路 这适用于@SOME_ID变量 ;WITH cte_recursive AS ( SELECT ID, SUB_ID FROM tableA WHERE SUB_ID = @SOME_ID UNION ALL SELECT parent.ID, parent.SUB
;WITH cte_recursive AS
(
SELECT ID, SUB_ID FROM tableA
WHERE SUB_ID = @SOME_ID
UNION ALL
SELECT parent.ID, parent.SUB_ID
FROM tableA parent
INNER JOIN cte_recursive child ON child.ID = parent.SUB_ID
)
我现在需要做的是,从表B中取出所有记录
并为CTE表达式使用tableB.SOME_ID,并在CTE生成的每个记录的TableC中创建一个insert,再加上tableB中的一些字段
(cte_recursive.CHILD_ID,tableB.SomeValue,tableB.SomeOtherValue)
我的问题是,如何将tableB.SOME_ID传递给cte表达式
所以在TableA中我得到了这样的东西:
身份证
1,2
2,3
2,4
2,5
5,6
7,8
8,9
如果我把SUB#u ID=5传递给他,CTE会将记录#1、#2、#3、#4、#5返回给我
因为SUB_ID=5是一个孩子的孩子的孩子的孩子。。。of ID=1我不知道你想要什么,所以就猜吧
;WITH cte_tableB AS
(
SELECT * FROM tableB
)
, cte_recursive AS
(
SELECT ID, SUB_ID, SOME_ID FROM tableA
WHERE SUB_ID IN (SELECT SOME_ID FROM cte_tableB)
UNION ALL
SELECT parent.ID, parent.SUB_ID, SOME_ID
FROM tableA parent
INNER JOIN cte_recursive child ON child.ID = parent.SUB_ID
)
INSERT [YourTable] ([YourColumns...])
SELECT [YourColumns...]
FROM cte_recursive
INNER JOIN cte_tableB ON cte_recursive.SomeID = cte_tableB.SomeID
您可以创建表值函数
create function ftBranchOf
(
@SOME_ID int -- actual type of @SOME_ID
)
returns table as return
(
WITH cte_recursive AS
(
SELECT ID, SUB_ID FROM tableA
WHERE SUB_ID = @SOME_ID
UNION ALL
SELECT parent.ID, parent.SUB_ID
FROM tableA parent
INNER JOIN cte_recursive child ON child.ID = parent.SUB_ID
)
select * from cte_recursive
)
然后在查询中使用它
insert into TableC (...)
select p.ID, b.SomeValue, b.SomeOtherValue
from TableB b
cross apply ftBranchOf(b.SOME_ID) p
只需在两个
SELECT
语句中加入tableB即可。我不能,因为在联合部分中,parent.ID和parent.Sub_ID都没有tableB条目。因为cte为1条tableA记录创建了n条记录。我会扩展我的开场白。我没想到,这部作品很有魅力。在搜索交叉应用于某些语法问题时发现此问题