llopx

能跟您分享知识,是我的荣幸

如何用动态SQL返回临时表的组合查询数据

 
Create table #table (num int,name1 nvarchar(10),name2 nvarchar(10))

Create table #table1 (num int, name1 nvarchar(10))
insert into #table1 
select 1,'a' union all select 2,'b'
Create table #table2 (num1 int, name2 nvarchar(10))
insert into #table2 
select 1,'aa' union All select 2,'bb'
declare @sqlstr nvarchar(1000) 
--

set @sqlstr = 'select a.*,b.name2 from #table1 as a inner join #table2 as b on a.num = b.num1 '

insert into #table 
exec  (@sqlstr)

select * from #table

drop table #table1
drop table #table2
drop table #table
 
按上面的这个方法,如果现在有这样的一种情况:
 
1.数据由多个临时表按组合查询,要形成一个大表,并且,大表里的数据比如主键,是不能重复的。
 
2.临时表的列字段不是固定的,有可能随机产生。
 
解决方法:
 
1.用@sql动态创建一个新的大表,里面包含了要产生的动态列字段。
 
2.用动态sql组合查询语法。
 
3.用exec执行查询语法,把结果集装到大表里。

posted on 2010-01-24 17:41  llopx  阅读(822)  评论(0编辑  收藏  举报

导航