数据记录分表后的查询问题

来源:百度知道 编辑:UC知道 时间:2024/09/21 06:39:50
主表
id x table_id
1 x1 扩展01
2 x2 扩展01
3 x3 扩展02
4 x4 扩展03
5 x5 扩展03
6 x6 扩展03
...

扩展01
id y
1 y1
2 y2
...

扩展02
id y
3 y3
...

扩展03
id y
4 y4
5 y5
6 y6
...

实现结果:
id x y
1 x1 y1
2 x2 y2
3 x3 y3
4 x4 y4
5 x5 y5
6 x6 y6
...
只所以把表名存入字段里就是因为扩展表比较多。可能上百成千的时候怎么处理呢?

declare @sql varchar(8000),@table_id varchar(20)
select @sql=''
declare ytbelwxg cursor for select distinct table_id from 主表
open ytbelwxg
fetch next from ytbelwxg into @table_id
while @@fetch_status=0
begin
select @sql=@sql+'select 主表.id,主表.x,'+@table_id+'.y from 主表,'+@table_id+' where 主表.id='+@table_id+'.id union all '
fetch next from ytbelwxg into @table_id
end
close ytbelwxg
deallocate ytbelwxg
select @sql=left(@sql,len(@sql)-len('union all '))

print @sql
exec (@sql)
以上,希望对你有所帮助!

--说说我的处理思路:
--首先你要整合所有扩展表,按统一格式汇总到一个张表,
--然后创建函数,
--如果表比较多,手写不能够实现,就用存储过程,
--我这里是手动用union all实现的,

--创建测试表,插入测试数据
select 1 id,'x1' x,'tb1' f3 into Tb
union all
select 2,'x2','tb1'
union all
select 3,'x3','tb2'
union all
select 4,'x4','t