select @cols =
STUFF((SELECT ',' + QUOTENAME(grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsRollup = STUFF((SELECT ', Sum(' + QUOTENAME(grade) + ') as '+QUOTENAME (grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT * into #temp3 from
(
SELECT lob as "Vertical", '+ @colsRollup + '
FROM
(
SELECT lob,' + @cols + ' from
(
select lob,
grade,
asso_count
from #temp
) x
pivot
(
count(grade)
for grade in (' + @cols + ')
) p
) x1
GROUP BY lob with ROLLUP)x2'
execute(@query)
我正在尝试创建动态列并将其插入到临时表中。但它会抛出一个错误,指出 #temp3 不是有效的对象名称。如果我不尝试将动态生成的列插入表中,则该代码有效。