2019-03-12
阅读量:
667
自关联更新的sql语句写法
问题描述:
想更新一个表内的数据,但是不知道怎么写sql语句,sqlserver下的,。
表结构:
fguid id name pid pname
2233 10 儿子 20 父亲
4455 20 父亲 30 爷爷
6677 30 爷爷 40 xx......
1、每段数据都有自己的父节点,我现在想把每一条数据的pid这个字段改成他的父节点的guid,例如:
2233 10 儿子 4455 父亲
2、还有一个就是如果我要将 2233 10 儿子 4455 null 中的null填上根据pid查找到的pname的值该怎么写?
解决方法:
if object_id('tempdb..#t') is not null drop table #t
create table #t (fguid int,id int,name nvarchar(10),pid int,pname nvarchar(10));
insert into #t
select 2233,10,N'儿子',20,N'父亲' union all
select 4455,20,N'父亲',30,N'爷爷' union all
select 6677,30,N'爷爷',40,N'xx' union all
select 8899,40,null,null,null
select * from #t
update t set t.pid=pt.fguid,set t.pname=pt.name from #t as t inner join #t as pt on pt.id=t.pid
select * from #t
更新前:

更新后:
id=40的pname为空,所以最后一行没更新







评论(0)


暂无数据
推荐帖子
0条评论
0条评论
1条评论