使用游标迭代sql数据

时间:2014-04-24 10:44:11

标签: sql sql-server sql-server-2008 tsql

所以,我有一个名为“bom”的SQL表。

  • ParentPartId
  • ChildPartId

想象一下,我有一些表格,例如(未知数量的子级别):

| PARENTPARTID  |  CHILDPARTID |
+---------------+--------------+
| NK-FS-DR-62DR | 2001020060   |
| 2001020060    | 2002014018   |
| 2002014018    | 120011       |
| NK-WH-DR-3MH  | 2001916023   |

基本上我想选择“NK-FS-DR-62DR”,它会选择它下面的所有子部件,看起来像

| PARENTPARTID  |  CHILDPARTID |
+---------------+--------------+
| NK-FS-DR-62DR | 2001020060   |
| 2001020060    | 2002014018   |
| 2002014018    | 120011       |

boms可以达到未知数量的深度。

所以,我正在寻找某种形式的光标来代替所有的子级。

我目前有一个游标,但我想不出迭代数据的方法。

这是我当前的代码(仅深入1级):

CREATE TABLE #tmpBillOfMaterial
(
    ParentPartId VARCHAR(18),
    ChildPartId VARCHAR(18)
)

DECLARE @ParentPartId VARCHAR(18)

INSERT INTO #tmpBillOfMaterial ( ParentPartId, ChildPartId )
SELECT b.ParentPartId, b.ChildPartId
FROM jbds.BoM b
WHERE b.ParentPartId = 'NK-FS-DR-62DR'

DECLARE cursorStage1 CURSOR FOR  
SELECT b.ChildPartId
FROM jbds.BoM b
WHERE b.ParentPartId = 'NK-FS-DR-62DR'

OPEN cursorStage1  
FETCH NEXT FROM cursorStage1 INTO @ParentPartId  

WHILE @@FETCH_STATUS = 0  
BEGIN  

    INSERT INTO #tmpBillOfMaterial ( ParentPartId, ChildPartId )
    SELECT b.ParentPartId, b.ChildPartId
    FROM jbds.BoM b
    WHERE b.ParentPartId = @ParentPartId

    FETCH NEXT FROM cursorStage1 INTO @ParentPartId  
END  

CLOSE cursorStage1  
DEALLOCATE cursorStage1 


SELECT *
FROM #tmpBillOfMaterial

DROP TABLE #tmpBillOfMaterial

我尝试在光标中添加光标,但只能获得2级深度,而不是迭代所有数据。

1 个答案:

答案 0 :(得分:5)

最简单的方法是使用递归CTE:

;with x as (
select parentpartid, childpartid
from bom
where parentpartid = 'NK-FS-DR-62DR'
union all
select bom.parentpartid, bom.childpartid
from bom
inner join x on bom.parentpartid = x.childpartid
)
select * from x