我在使用SQL Server 2008的存储过程中进行了动态数据透视查询。
示例
create proc testing
@tablename varchar(10),
@col varchar(10)
AS
Declare @cols nvarchar(max),
@query nvarchar(max)
SET @cols = N'SELECT STUFF((SELECT '','' + QUOTENAME('+ @col +')
from ' + @ViewName + '
group by ' + @col + '
order by ' + @col + '
FOR XML PATH(''''), TYPE
).value(''.'', ''NVARCHAR(MAX)'')
,1,1,'''')'
execute(@cols)
set @query = 'SELECT '+ @cols + '
From
(
SELECT ' + @col + '
from ' + @tablename + '
) x
pivot
(
count(' + @col +')
for ' + @col + ' in (' + @cols + ')
) p '
exec sp_executesql @query;
Go
调用功能:
execute testing @tablename = 'test1',@col = 'item'
注意仅执行@cols
STUFF
但未执行@query
。我没有得到我错的地方。