本帖最后由 daisyding1984 于 2013-01-17 11:06:41 编辑

解决方案 »

  1.   

    分是低了點.不過重點是,類似題目你已經發了到少3個了吧.前面的貼子你改改也就可以實現了.
    http://bbs.csdn.net/topics/390348835
      

  2.   

    USE test
    GO-->生成表tbif 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
      头饰              1
      手表              2
      挂件              3
       皮帶手表        1
       石英手表        2
     女性用品(封面频道)  2
      彩妆              1
      护肤              2
     精致礼品(封面频道)  3
      玩具              1
      动漫              2
      桌游              3
     日常用品(封面频道)  4
      数码配件          1
      手提包            2
      皮夹              3*/