如何实现如下更新啊,在线等

bcsky 2005-08-22 11:30:12
id name
---------------------------------------------
130000 河北省
130100 石家庄市
130101 市辖区
130102 长安区
130103 桥东区
130200 唐山市
130201 市辖区
130202 路南区
数据如上,需要更新name字段数据,更新后数据显示为
id name
---------------------------------------------
130000 河北省
130100 河北省石家庄市
130101 河北省石家庄市市辖区
130102 河北省石家庄市长安区
130103 河北省石家庄市桥东区
130200 河北省唐山市
130201 河北省唐山市市辖区
130202 河北省唐山市路南区

也就是二级城市加上省名称,三级加上省和市,
请大家帮忙看看啊,谢谢!
...全文
76 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
子陌红尘 2005-08-22
  • 打赏
  • 举报
回复
服务器: 消息 512,级别 16,状态 1,行 1
子查询返回的值多于一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
语句已终止。


好象有错误
-------------------------------------------------------------------
应该是你使用的测试数据有问题,表中存在重复记录。
ywqxtx 2005-08-22
  • 打赏
  • 举报
回复
服务器: 消息 512,级别 16,状态 1,行 1
子查询返回的值多于一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
语句已终止。


好象有错误
子陌红尘 2005-08-22
  • 打赏
  • 举报
回复
--生成测试数据
create table #t(id int,name varchar(100))
insert into #t select 130000,rtrim('河北省')
insert into #t select 130100,rtrim('石家庄市')
insert into #t select 130101,rtrim('市辖区 ')
insert into #t select 130102,rtrim('长安区 ')
insert into #t select 130103,rtrim('桥东区 ')
insert into #t select 130200,rtrim('唐山市 ')
insert into #t select 130201,rtrim('市辖区 ')
insert into #t select 130202,rtrim('路南区 ')
go


--执行更新语句
update
a
set
name = (select name from #t where id/10000=a.id/10000 and id%10000=0)
+ (case id%100 when 0 then '' else (select name from #t where id/100=a.id/100 and id%100=0) end)
+ a.name
from
#t a
where
id%10000 != 0


--查询更新结果
select * from #t

--输出结果
id name
------ --------------------
130000 河北省
130100 河北省石家庄市
130101 河北省石家庄市市辖区
130102 河北省石家庄市长安区
130103 河北省石家庄市桥东区
130200 河北省唐山市
130201 河北省唐山市市辖区
130202 河北省唐山市路南区
子陌红尘 2005-08-22
  • 打赏
  • 举报
回复
drop table #t


create table #t(id int,name varchar(100))
insert into #t select 130000,rtrim('河北省')
insert into #t select 130100,rtrim('石家庄市')
insert into #t select 130101,rtrim('市辖区 ')
insert into #t select 130102,rtrim('长安区 ')
insert into #t select 130103,rtrim('桥东区 ')
insert into #t select 130200,rtrim('唐山市 ')
insert into #t select 130201,rtrim('市辖区 ')
insert into #t select 130202,rtrim('路南区 ')
go

update
a
set
name = (select name from #t where id/10000=a.id/10000 and id%10000=0)
+ (case id%100 when 0 then '' else (select name from #t where id/100=a.id/100 and id%100=0) end)
+ a.name
from
#t a
where
id%10000 != 0

select * from #t
子陌红尘 2005-08-22
  • 打赏
  • 举报
回复
update
t a
set
name = (select name from t where id%1000=t.id%10000 and id%10000=0)
+ (case id%100 when 0 then '' else (select name from t where id%100=t.id%100 and id%100=0) end)
+ a.name
where
id%10000 != 0
bcsky 2005-08-22
  • 打赏
  • 举报
回复
to:libin_ftsafe(子陌红尘)
非常感谢您的帮助,问题已解决。

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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