DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
-- 获取不重复的AttributeName列表
SELECT @columns =
STUFF((SELECT DISTINCT ',' + QUOTENAME(attriname)
FROM ProClass_Attri
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
-- 构建并执行动态PIVOT查询
SET @sql = '
SELECT classid, ' + @columns + '
FROM (
SELECT classid, attrivalue, attriname
FROM ProClass_Attri
) AS SourceTable
PIVOT (
MAX(attrivalue)
FOR attriname IN (' + @columns + ')
) AS PivotTable';
EXEC sp_executesql @sql;