BOM数据排序及分级显示
--示例数据: CREATE TABLE BomSub(Parent_item varchar(10),Sub_item varchar(10)) INSERT BomSub SELECT 'A' ,'AA' UNION ALL SELECT 'A' ,'AB' UNION ALL SELECT 'AA' ,'AAA' UNION ALL SELECT 'AA' ,'AAB' GO
问题描述: Parent_item是父项,Sub_item是子项,根据根据父子关系排序,并生成每个项目的层次。对于示例数据,要求结果如下: Parent_item LEVEL ----------- ------- A 0 |-AA 1 |--AAA 2 |--AAB 2 |-AB 1
(所影响的行数为 5 行)
--查询处理的存储过程 CREATE PROC P_QRY AS DECLARE @t TABLE(Parent_item varchar(10),Level int,Path varchar(8000)) DECLARE @l int SET @l=0 INSERT @t SELECT DISTINCT Parent_item,@l,RIGHT(SPACE(20)+Parent_item,20) FROM BomSub a WHERE NOT EXISTS( SELECT * FROM BomSub WHERE Sub_item=a.Parent_item) WHILE @@ROWCOUNT>0 BEGIN SET @l=@l+1 INSERT @t SELECT a.Sub_item,@l,b.Path+RIGHT(SPACE(20)+a.Sub_item,20) FROM BomSub a,@t b WHERE a.Parent_item=b.Parent_item AND b.Level=@l-1 END SELECT Parent_item=CASE Level WHEN 0 THEN '' ELSE '|'+REPLICATE('-',Level) END+Parent_item, Level FROM @t ORDER BY Path GO
--调用 EXEC P_QRY
1.I want to figure out that what is the ' @@ROWCOUNT
--SQL Code1: insert bomsub select'B','BB' union select'BB','BBB'
DECLARE @t TABLE(Parent_item varchar(10),Level int,Path varchar(8000)) DECLARE @l int SET @l=0 INSERT @t SELECT DISTINCT Parent_item,@l,RIGHT(SPACE(20)+Parent_item,20) FROM BomSub a WHERE NOT EXISTS( SELECT * FROM BomSub WHERE Sub_item=a.Parent_item)
select @@ROWCOUNT
select * from @t
select * from bomsub /* No column name 2
parent_item level path A 0 A B 0 B
|