sql存储过程转列例子
ALTER procedure PropertGetPivot as Begin DECLARE @ColumnNames VARCHAR(3000) SET @ColumnNames='' SELECT @ColumnNames = @ColumnNames + '[' + [getDeptID] + '],' FROM ( SELECT DISTINCT getDeptID FROM [pArticleGet] group by [getDeptID] )t SET @ColumnNames= LEFT(@ColumnNames, LEN(@ColumnNames)-1) DECLARE @selectSQL NVARCHAR(3000) SET @selectSQL= 'SELECT DeptId,ArticleId,{0} FROM (SELECT DeptId,ArticleId,getDeptID,SUM(GetAmount)GetAmount FROM [AffairMS].[dbo].[pArticleGet] group by DeptId,ArticleId,getDeptID) p Pivot(max(GetAmount) For getDeptID in ({0})) AS pvt ORDER BY ArticleId' SET @selectSQL= REPLACE(@selectSQL,'{0}',@ColumnNames) exec sp_executesql @selectSQL end