[英]How to use #tmp Table in Loop in Recursive Function
我正在嘗試創建一個循環,當給定零件 ID 時,它將搜索裝配零件表並將所有零件分解成一個大列表。
它需要遞歸,因為第 123 部分可能有第 1、2、3、4、5 部分,第 4 和第 5 部分也是裝配項。 我以為我想出了一些非常好的東西,並且很容易返回每個項目的零件 ID 和零件級別。 然后我發現我不能使用臨時表,所以它把我的循環打斷了。
我可以用什么代替臨時表在這里給我相同的 function?
CREATE FUNCTION [dbo].[fn_getParts] (
@source_part_id int
, @level int
)
RETURNS @parts_list TABLE (
[part] int NOT NULL,
[level] int NOT NULL
)
AS
BEGIN
DECLARE
@max int = 0,
@cnt int = 0,
@PID int = 0,
@Plvl int = 0,
@id int = 0
INSERT INTO @parts_list VALUES (@source_part_id, @level)
SET @level += 1
SELECT [Comp_Part_ID] AS [PID], @level AS [level]
INTO #chkParts
FROM [assemblies]
WHERE [Assy_PID] = @source_part_id
SELECT @max = COUNT(*) FROM #chkParts
WHILE @cnt <= @max
BEGIN
SELECT @PID = [PID], @Plvl = [level] FROM #chkParts
INSERT INTO @parts_list
SELECT * FROM [fn_getParts](@PID, @Plvl)
SET @cnt += 1
END
RETURN
END
以下是一些示例數據:
CREATE TABLE [Assemblies] (
[PartID] int,
[Comp_PartID] int
)
INSERT INTO [Assemblies] VALUES
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(3,9),
(3,10),
(10,11),
(10,23),
(10,24),
(10,31),
(11,24),
(11,23)
如果我輸入SELECT * FROM [fn_getParts](1,0)
我會期望以下內容:
part,level
1,0
2,1
3,1
4,1
9,2
10,2
11,3
23,3
24,3
通過將內聯表值 Function 包裹在遞歸 CTE 周圍,可以稍微簡化代碼,例如:
create function dbo.fn_getParts (
@source_part_id int
)
returns table as return (
with PartsHierarchy as (
select @source_part_id as part, 0 as level
union all
select Comp_PartID, 1 + level
from Assemblies
join PartsHierarchy on part = PartID
)
select part, level
from PartsHierarchy
);
然后,為不同的零件號調用它......
select * from dbo.fn_getParts(1);
part level
---- ----
1 0
2 1
3 1
4 1
5 1
6 1
9 2
10 2
11 3
23 3
24 3
31 3
24 4
23 4
select * from dbo.fn_getParts(10);
part level
---- -----
10 0
11 1
23 1
24 1
31 1
24 2
23 2
select * from dbo.fn_getParts(11);
part level
---- -----
11 0
24 1
23 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.