大哥们帮个忙啊,谢谢(关于检索赋值)

codepagetwo 2007-08-28 01:44:01
原表是这样的:
id号 字段A 字段B
1 tttt null
2 gggg null
3 ffff 1
4 bbbb 1
5 hhhh 2

要得到的结果是:
id号 字段A 字段B
1 tttt null
2 gggg null
3 tttt 1
4 tttt 1
5 gggg 2

需求大致是:字段B为空的记录不处理。根据字段B里面的ID号,将字段A重新赋值成这个ID号对应的字段A里面的值。

我试过用嵌套查询更新,但提示“子查询返回的值多于一个。”。。可能用到游标麽?
恳请各位大侠帮忙。。
我是这么写的
update table set 字段A=(select 字段A from table where id=(select 字段B from table))
...全文
124 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
codepagetwo 2007-08-28
  • 打赏
  • 举报
回复
哥,,你实在是太强了,。我佩服的五体投地。。。
再次感谢你,大哥
chuifengde 2007-08-28
  • 打赏
  • 举报
回复
update a set a.字段a=case when a.字段b is null then a.字段a else b.字段a end from @a a left join @a b on a.字段b=b.id号
dawugui 2007-08-28
  • 打赏
  • 举报
回复
create table tb(id int , A varchar(10) , B int)
insert into tb values(1, 'tttt', null)
insert into tb values(2, 'gggg', null)
insert into tb values(3, 'ffff', 1)
insert into tb values(4, 'bbbb', 1)
insert into tb values(5, 'hhhh', 2)
go
update tb
set a = t.a
from tb,tb t
where tb.b is not null and tb.b = t.id
select * from tb
drop table tb

/*
id A B
----------- ---------- -----------
1 tttt NULL
2 gggg NULL
3 tttt 1
4 tttt 1
5 gggg 2
(所影响的行数为 5 行)
*/
dawugui 2007-08-28
  • 打赏
  • 举报
回复
create table tb(id int , A varchar(10) , B int)
insert into tb values(1, 'tttt', null)
insert into tb values(2, 'gggg', null)
insert into tb values(3, 'ffff', 1)
insert into tb values(4, 'bbbb', 1)
insert into tb values(5, 'hhhh', 2)
go
update tb
set a = t.a
from tb,(select * from tb where b is null) t
where tb.b is not null and tb.b = t.id
select * from tb
drop table tb

/*
id A B
----------- ---------- -----------
1 tttt NULL
2 gggg NULL
3 tttt 1
4 tttt 1
5 gggg 2

(所影响的行数为 5 行)

*/
dawugui 2007-08-28
  • 打赏
  • 举报
回复
update tb
set a = t.a
from tb , tb a
where tb.b = a.id

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧