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执行查询语法,把结果集装到大表里。

相关文章:

  • 2022-12-23
  • 2021-12-10
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2021-11-21
  • 2022-12-23
  • 2021-12-27
猜你喜欢
  • 2021-06-30
  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-09
  • 2021-06-23
相关资源
相似解决方案