[Transact-SQL] BOM 노드별 정렬

2921 단어
문제는 다음과 같습니다.
CREATE TABLE [dbo].[BOM_Table](
	[Code] [nvarchar](50) NULL,
	[Z_Name] [nvarchar](50) NULL,
	[B_Code] [nvarchar](50) NULL,
	[B_Name] [nvarchar](50) NULL
) ON [PRIMARY]

GO
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('1001','   ','10089','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('1001','   ','10063','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('1001','   ','10082','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('1001','   ','10081','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('10063','  ','102331','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('10063','  ','102303','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('102303','  ','203301','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('102303','  ','203302','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('10082','  ','205410','  ')
INSERT INTO BOM_Table(Code,Z_Name,B_Code,B_Name)
VALUES('10082','  ','205418','  ')

--------  ---------------------------------------------
--    ,         ,              ,    ,           
--       ,       ,               。
---                ------

Code	Z_Name	B_Code	B_Name	    
1001	   	10089	  	1
1001	   	10063	  	1
10063	  	102331	  	1-1
10063	  	102303	  	1-2
102303	  	203301	  	1-2-1
102303	  	203302	  	1-2-2
1001	   	10082	  	1
10082	  	205410	  	1-1
10082	  	205418	  	1-2
1001	   	10081	  	1

이 쓰기 방법은 not exists를 통해 루트 노드를 찾은 다음 루트 노드부터 서브 노드로 옮겨다니며sort 필드를 통해 정렬하고 속성 필드는 차원 level에 rownum을 조합하여 만든다.
;with tt 
as 
(
  select *, 
         row_number() over (partition by Code order by getdate()) rownum
  from   [BOM_Table]
)
 
,t as
(
select tt.[Code],tt.[Z_Name],tt.[B_Code],tt.[B_Name],
       cast(1 as varchar(100)) level ,
       CAST(rownum as varchar(100)) sort
from tt 
where not exists(select 1 from tt a where tt.code = a.b_code)

union all

select tt.[Code],tt.[Z_Name],tt.[B_Code],tt.[B_Name],
       cast(t.level+'-'+cast(tt.rownum as varchar(100)) as varchar(100)),
       cast(t.sort+'-'+cast(tt.rownum as varchar(100)) as varchar(100))
from t
inner join tt
        on tt.Code = t.B_Code
)


select [Code],[Z_Name],[B_Code],[B_Name],
       level as     
from t 
order by sort
/*
Code	Z_Name	B_Code	B_Name	    
1001	   	10089	  	1
1001	   	10063	  	1
10063	  	102331	  	1-1
10063	  	102303	  	1-2
102303	  	203301	  	1-2-1
102303	  	203302	  	1-2-2
1001	   	10082	  	1
10082	  	205410	  	1-1
10082	  	205418	  	1-2
1001	   	10081	  	1
*/

좋은 웹페이지 즐겨찾기