一张表..本来只有ID,ParentID字段
如这样:
ID  ParentID
1      null
2      null
3      1
4      3
5      4
....
现在加了一个字段 PIDs
想通过一条UPDATE 语句来实现下面这种结果...
ID  ParentID  PIDs
1      null     null
2      null     null
3      1        1
4      3        1,3
5      4        1,3,4
....只要一条语句哦...可以吗..不行多条也行...
能否...不过也应该很基础地吧...?

解决方案 »

  1.   

    if object_id('tb') is not null drop table tb
    go
    create table tb(ID int, ParentID int)
    insert tb
    select 1 , null union all
    select 2 , null union all 
    select 3 , 1 union all 
    select 4 , 3 union all 
    select 5 , 4 alter table tb add  PIDs varchar(200)declare @i varchar(200)update tb set pids=stuff(@i,1,1,''),
                  @i=isnull(@i,'')+','+ltrim(ParentID)select * from tb
    drop table tbID          ParentID    PIDs
    ----------- ----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    1           NULL        NULL
    2           NULL        NULL
    3           1           1
    4           3           1,3
    5           4           1,3,4(5 行受影响)