一张表..本来只有ID,ParentID字段
如这样:
ID ParentID
a null
b null
c a
d b
e g
f c
g d
h g
i e
....
现在加了一个字段 PIDs
想通过一条UPDATE 语句来实现下面这种结果...
ID ParentID PIDs
a null null
b null null
c a a
d b b
e g b,d,g
f c a,c
g d b,d
h g b,d,g
i e b,d,g,e
.... 以i为例,i的PIDs等于 i的ParentID 也就是 e 的PIDs + ',' + e.... 只要一条语句哦...可以吗..不行多条也行...
能否...不过也应该很基础地吧...?
如这样:
ID ParentID
a null
b null
c a
d b
e g
f c
g d
h g
i e
....
现在加了一个字段 PIDs
想通过一条UPDATE 语句来实现下面这种结果...
ID ParentID PIDs
a null null
b null null
c a a
d b b
e g b,d,g
f c a,c
g d b,d
h g b,d,g
i e b,d,g,e
.... 以i为例,i的PIDs等于 i的ParentID 也就是 e 的PIDs + ',' + e.... 只要一条语句哦...可以吗..不行多条也行...
能否...不过也应该很基础地吧...?
where a.id in(select c.id from a as c where c.parentid is not null)不知道是否可行 没环境这里。。
--这个函数,字段大小改一下,表名改一下
create function getPids(@id nchar(1))
returns varchar(20)
as
begin
declare @pid nchar(1)
declare @rst varchar(20)
select @pid=ParentID from tbl_Dpt where id=@id
while(@pid is not null)
begin
set @rst = isnull(@rst,'')+@pid+','
select @pid=ParentID from tbl_Dpt where id=@pid
end
return stuff(@rst,len(@rst),1,'')
end
id parentid pids
---- -------- --------------------
a NULL NULL
b NULL NULL
c a a
d b b
e g g,d,b
f c c,a
g d d,b
h g g,d,b
i e e,g,d,b
update tbl_Dpt set pids=dbo.getPids(id)