怎样将EXEC()的结果保存为临时表
类似于下面的与语句,如何将EXEC(@sql)结果保存到临时表中?CREATE TABLE #Test ( [id] [int] IDENTITY (1, 1) NOT NULL , [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [Source] [numeric](18, 0) NULL ) ON [PRIMARY]
GO
INSERT INTO #Test ([name],[subject],[Source]) values (N'张三',N'ch',60)
INSERT INTO #Test ([name],[subject],[Source]) values (N'李四',N'ma',70)
INSERT INTO #Test ([name],[subject],[Source]) values (N'王五',N'eg',80)
INSERT INTO #Test ([name],[subject],[Source]) values (N'王五',N'ma',75)
INSERT INTO #Test ([name],[subject],[Source]) values (N'王五',N'ch',57)
INSERT INTO #Test ([name],[subject],[Source]) values (N'李四',N'ch',80)
INSERT INTO #Test ([name],[subject],[Source]) values (N'张三',N'eg',100)
Go
declare @sql varchar(8000)
set @sql = 'select name,'
select @sql = @sql + 'sum(case subject when '''+subject+''' then source else 0 end) as '''+subject+''','
from (select distinct subject from #test) as a
select @sql = left(@sql,len(@sql)-1) + ' from #test group by name'
exec(@sql)
go
这里的重点是subject列内的内容数量是变化且不确定的,所以如果使用create table (***,int……) insert …… 这样先创建表的时候是无法准确预定义列名和列数量的。
请指教!