110,533
社区成员
发帖
与我相关
我的任务
分享
--测试数据begin
create table 总表(类型 nchar(1),编码 nchar(3))
insert into 总表
select 'A','001' UNION ALL
select 'B','002' UNION ALL
select 'C','003'
create table [001](ID int,编码 nchar(3),X坐标 int,Y坐标 int)
insert into [001]
select 1 , '001', 12, 32 union all
select 2 , '001', 33, 32
create table [002](ID int,编码 nchar(3),X坐标 int,Y坐标 int)
insert into [002]
select 1 , '002', 33, 55 union all
select 2 , '002', 44, 32
create table [003](ID int,编码 nchar(3),X坐标 int,Y坐标 int)
insert into [003]
select 1 , '003', 1, 2 union all
select 2 , '003', 44, 66
--测试数据end
--查询部分begin
declare @sql varchar(8000)
set @sql=''
select @sql = @sql+' select 总表.类型,总表.编码,X坐标,Y坐标 from 总表 left join ['+编码+']
on 总表.编码=['+编码+'].编码 where 总表.编码='''+编码+''' union all'
from 总表
set @sql = stuff(@sql,len(@sql)-9,10,'')
exec(@sql)
--查询部分end
drop table 总表
drop table [001]
drop table [002]
drop table [003]
/*输出
类型 编码 X坐标 Y坐标
---- ---- ----------- -----------
A 001 12 32
A 001 33 32
B 002 33 55
B 002 44 32
C 003 1 2
C 003 44 66
*/
select 类型,编码,x,y from 总表 left join 分表1 on 总表.编码=分表1.编码 where 总表.编码='001'
union all
select 类型,编码,x,y from 总表 left join 分表2 on 总表.编码=分表2.编码 where 总表.编码='002'
union all
select 类型,编码,x,y from 总表 left join 分表3 on 总表.编码=分表3.编码 where 总表.编码='003'