日期:2014-05-17 浏览次数:20954 次
USE test
GO
-->生成表tb
if object_id('tb') is not null
drop table tb
Go
Create table tb([CatId] smallint,[CatName] nvarchar(4),[ParentId] smallint,[SortOrder] smallint,[CatAttr] bit)
Insert into tb
Select 2,N'产品专区',0,1,1
Union all Select 5,N'精美饰品',2,1,1
Union all Select 6,N'女性用品',2,2,1
Union all Select 7,N'精致礼品',2,3,1
Union all Select 8,N'日常用品',2,4,1
Union all Select 33,N'头饰',5,1,0
Union all Select 10,N'手表',5,2,0
Union all Select 11,N'挂件',5,3,0
Union all Select 14,N'彩妆',6,1,0
Union all Select 15,N'护肤',6,2,0
Union all Select 19,N'玩具',7,1,0
Union all Select 20,N'动漫',7,2,0
Union all Select 21,N'桌游',7,3,0
Union all Select 25,N'数码配件',8,1,0
Union all Select 26,N'手提包',8,2,0
Union all Select 27,N'皮夹',8,3,0
Union all Select 28,N'皮帶手表',10,1,0 ---- test
Union all Select 29,N'石英手表',10,2,0 ---- test
;WITH t AS (
SELECT
CatId
,CAST(CatName AS NVARCHAR(50)) AS CatName
,ParentId
,SortOrder
,CatAttr
,1 AS row
,CAST(0 AS INT) AS row1
FROM tb
WHERE ParentId=0
UNION ALL
SELECT
a.CatId
,CAST(REPLICATE(' ',row)+a.CatName AS NVARCHAR(50)) AS CatName
,a.ParentId
,a.SortOrder
,a.CatAttr
,b.row+1
,CAST(CASE WHEN b.ParentId=0 THEN ROW_NUMBER()OVER(ORDER BY a.SortOrder) ELSE b.row1 END AS INT)
FROM tb AS a
INNER JOIN t AS b ON a.ParentId=b.CatId
)
SELECT
CatName+CASE WHEN CatAttr=1 THEN N'(封面频道)' ELSE '' END AS CatName
,SortOrder
FROM t
ORDER BY row1,ParentId,SortOrder
/*
CatName SortOrder
--------------------- ---------
产品专区(封面频道) 1
精美饰品(封面频道) 1
头饰 &