比如:
一张表A是专门存放城市的
————————
id city
1 福州
2 厦门
3 广州
————————
另一张表B中有个字段是可以存储多个城市的(数据取自A表)
————————
citys
福州,厦门
福州,广州
————————
表结构设计的时候没有用外键关联,那如果A表中更新数据的时候,B中要怎么更新?
一张表A是专门存放城市的
————————
id city
1 福州
2 厦门
3 广州
————————
另一张表B中有个字段是可以存储多个城市的(数据取自A表)
————————
citys
福州,厦门
福州,广州
————————
表结构设计的时候没有用外键关联,那如果A表中更新数据的时候,B中要怎么更新?
use tempdb
goset nocount oncreate table #a
(
id int identity(1,1),
city varchar(10),
)create table #b
(
citys varchar(1000)
)
goinsert #a select '福州'
union all select '厦门'
union all select '广州'
insert #b select '福州,厦门'
union all select '福州,广州'
gocreate proc #p
@old_city varchar(10),
@new_city varchar(10)
as
set nocount onbegin tranupdate #a
set city = @new_city
where city = @old_city
if @@error<>0
begin
rollback tran
return
endupdate #b
set citys = replace(citys,@old_city,@new_city)
where charindex(@old_city,citys) > 0
if @@error<>0
begin
rollback tran
return
endcommit tran
goexec #p '福州','上海'
goselect * from #a
select * from #b
godrop proc #p
drop table #a
drop table #b
go/**
1 上海
2 厦门
3 广州
上海,厦门
上海,广州**/
insert #tbcity select '福州,厦门'
union all select '福州,广州'
union all select'福州,成都'
GO
select * from #tbcity
结果:
1 福州,厦门
2 福州,广州
3 福州,成都create procedure p_Updatecity
@oldCity varchar(20),
@newCity varchar(20)
AS
Begin update #tbcity set city=replace(city,@oldCity,@newCity)
where charindex(@oldCity,city)>0
if(@@error<>0)
rollback tran
end
GO
exec p_Updatecity '福州','上海'select * from #tbcitydrop table #tbcity
drop procedure p_Updatecity
查询后结果:
1 上海,厦门
2 上海,广州
3 上海,成都