两张表:
tjxxm(检修项目表<一对一表>),tsjsb(检修项目涉及的设备表<一对多表>)
tjxxm中数据:
cbm jxxmbh jxxmmc (厂编码,检修项目编号,检修项目名称)
01 2003001 1st_prj
01 2003002 2nd_Prj
tsjsb中数据:
cbm jxxmbh sjsbmc (厂编码,检修项目编号,涉及设备名称)
01 2003001 #1电机
01 2003001 #2水泵 查询得到的结果,希望使一对多关系的多方的那个表(如tsjsb表)的‘涉及设备名称’字段的数据合并成查询结果的唯一记的涉及设备字段的值; 也就是将一对多关系表查询成一对一表! 期望查询结果:
cbm jxxmbh jxxmmc sjsbmc
01 2003001 1st_prj #1电机,#2水泵
01 2003002 2nd_prj
希望高手帮忙 !!!!!!!!
into #Datas
from tjxxm z--取数据
declare @ID int, @tmp varchar(8000)
set @ID=0
while 1=1 do
begin
--取最小的ID号的没有生成sjsbmc的记录
select min(atID) from #Datas where atID>@ID
--没有记录就退出WHILE
if @@rowcount<=0 break
--设置@tmp为空串
set @tmp=''
--查出该所有的sjsbmc用逗号分开
update #Datas
set @tmp=@tmp+x.sjsbmc+','
from tsjsb x
where x.cbm=#Datas.cbm and
x.jxxmbh=#Datas.jxxmbh
--更新#Datas表
update #Datas
set sjsbmc=@tmp
where atID=@ID
end--return
select cbm, jxxmbh, jxxmmc, sjsbmc
from #Datasdrop table #Datas/*
我现在在网吧,
没有环境测试,
只能凭印象啦,
你自己再试试看吧,
不行再发信息给我。
*/
return varchar2
is
cursor t_sor is select sjsbmc from tsjsb where cbm=cbm1 and jxxmbh=jxxmbh1;
str varchar2(4000);
begin
for v_sor in t_sor loop
str:=str||v_sor.sjsbmc||',';
end loop;
return substr(str,1,length(str)-1);
end ;