日期:2014-05-19  浏览次数:20403 次

如何一次性显示出 某一层下所有子节点 返回表
create   table   tb(id   int   identity(1,1)   not   null   constraint   PK_tb   primary   key   clustered
,pid   int,name   varchar(20))
insert   into   tb
select   0, '中国 '
union   all   select   0, '美国 '
union   all   select   0, '加拿大 '
union   all   select   1, '北京 '
union   all   select   1, '上海 '
union   all   select   1, '江苏 '
union   all   select   6, '苏州 '
union   all   select   7, '常熟 '
union   all   select   6, '南京 '
union   all   select   6, '无锡 '
union   all   select   2, '纽约 '
union   all   select   2, '旧金山 '
union   all   select   4, '旧金山1 '
union   all   select   5, '旧金山2 '
 
go

select   *   from   tb
如何一次性显示出   某一层下所有子节点      

传入参数1   层   得到

id             Sort
----------------
1               4,5,6,7,8,9,10,13,14
2               11,12
3              
传入参数2   层   得到
id             Sort
----------------
4               13
5               14
6               7,9,10
11
12


-----问题2
或者返回   这样的语句   形式
传入参数1   层   得到
SELECT      
id1=StateName=sum(  
CASE       id
            WHEN   4   THEN   0
            WHEN   5   THEN   0
            WHEN   6   THEN   0
            WHEN   7   THEN   1
            WHEN   8   THEN   2
            WHEN   9   THEN   3
            WHEN   10   THEN   1
            WHEN   13     THEN   0
              WHEN   14     THEN   0
            END  
,
id2=StateName=sum(  
        CASE       id
            WHEN   11   THEN   0
            WHEN   12     THEN   0
           
            END  
)
FROM     tb


------解决方案--------------------
create table
tb
(
id int identity(1,1) not null constraint PK_tb primary key clustered
,pid int,
name varchar(20)
)
insert into tb
select 0, '中国 '
union all select 0, '美国 '
union all select 0, '加拿大 '
union all select 1, '北京 '
union all select 1, '上海 '
u