多表update问题,在线等。
表fm,fl表为父子表
表fm pk(id)
id range
200610001 null
200610002 null
200610003 null
表fl pk(id,pno)
id pno dno
200610001 1 2006Y0012
200610001 2 2006Y0013
200610001 3 2006Y0014
200610001 4 2006Y0015
200610002 1 2006Y0016
200610002 2 2006Y0017
200610003 1 2006Y0018
现在要求更新fm表,是range为如下形式:
id range
200610001 2006Y0012-2006Y0015
200610002 2006Y0016-2006Y0017
200610003 2006Y0018-2006Y0018
非常着急,请各位帮忙。谢谢!
------解决方案--------------------update fm set range=x from fm,(select id, min(dno)+ '- '+max(dno) x from fl group by id) bb where fm.id=bb.id
------解决方案--------------------create table fm(id varchar(10),range varchar(40))
insert into fm values( '200610001 ',null)
insert into fm values( '200610002 ',null)
insert into fm values( '200610003 ',null)
create table fl(id varchar(10),pno int,dno varchar(10))
insert into fl values( '200610001 ',1, '2006Y0012 ')
insert into fl values( '200610001 ',2, '2006Y0013 ')
insert into fl values( '200610001 ',3, '2006Y0014 ')
insert into fl values( '200610001 ',4, '2006Y0015 ')
insert into fl values( '200610002 ',1, '2006Y0016 ')
insert into fl values( '200610002 ',2, '2006Y0017 ')
insert into fl values( '200610003 ',1, '2006Y0018 ')
update t
set
range= (select dno from fl f where f.id=t.id and not exists(select 1 from fl where id=f.id and pno <f.pno))
+ '- '+(select dno from fl f where f.id=t.id and not exists(select 1 from fl where id=f.id and pno> f.pno))
from
fm t
select * from fm
/*
id range
---------- ----------------------------------------
200610001 2006Y0012-2006Y0015
200610002 2006Y0016-2006Y0017
200610003 2006Y0018-2006Y0018
*/
drop table fm,fl
------解决方案--------------------declare @id varchar(20)
declare @range varchar(30)
DECLARE fm_cursor CURSOR
FOR SELECT * FROM fm
OPEN fm_cursor
FETCH NEXT FROM fm_cursor into @id
WHILE @@FETCH_STATUS = 0
begin
select @range=min(dno)+ '- '+max(d