读书人

这个update语句如何写

发布时间: 2012-01-09 21:05:42 作者: rapoo

这个update语句怎么写?
create table #test(a int,b varchar(20))
insert into #test select 1, 'aaa '
insert into #test select 1,null
insert into #test select 1,null
insert into #test select 2,null
insert into #test select 2, 'bbbb '
insert into #test select 2,null
insert into #test select 3, 'cccc '

把上表中b字段为null的update为同a字段中b的值
---------------------->
select * from #test
1, 'aaa '
1, 'aaa '
1, 'aaa '
2, 'bbbb '
2, 'bbbb '
2, 'bbbb '
3, 'cccc '

这个update语句怎么写?

[解决办法]
create table #test(a int,b varchar(20))
insert into #test select 1, 'aaa '
insert into #test select 1,null
insert into #test select 1,null
insert into #test select 2,null
insert into #test select 2, 'bbbb '
insert into #test select 2,null
insert into #test select 3, 'cccc '

--把上表中b字段为null的update为同a字段中b的值

update a set a.b=b.b from #test a join (select * from #test where b is not null) b on a.a=b.a

select * from #test

/*
1, 'aaa '
1, 'aaa '
1, 'aaa '
2, 'bbbb '
2, 'bbbb '
2, 'bbbb '
3, 'cccc '

--这个update语句怎么写?
*/

drop table #test

读书人网 >SQL Server

热点推荐