日期:2014-05-18  浏览次数:20623 次

根据同一张表更新同一张表字段内容sql
表a的某些字段更新:
字段 1 acno
字段 2 acname
现在a的记录有些acname是空的,有的有,现在想把同一个acno的acname空的填写好,怎么写sql啊?
如:
12345 abcde
12345  
12345 abcde
12344 bcdef


现在我想把第二条的acname也修改成abcde,怎么写sql啊?

------解决方案--------------------
SQL code
create table a(acno varchar(10),acname varchar(10))
insert into a values('12345', 'abcde')
insert into a values('12345', null   )
insert into a values('12345', 'abcde')
insert into a values('12344', 'bcdef')
go

update a set acname = (select top 1 acname from a where acno = t.acno and acname <> '' and acname is not null) from a t where acname = '' or acname is null

select * from a
/*
acno       acname     
---------- ---------- 
12345      abcde
12345      abcde
12345      abcde
12344      bcdef

(所影响的行数为 4 行)
*/

drop table a

------解决方案--------------------
前面一个有错
SQL code

update table_name
set acname = (select top 1 t.acname from table_name t where t.acno = table_name.acno and t.acname is not null)
where acname is null