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

 



 

 

posted @ 2012-09-27 14:36  卢青松  阅读(204)  评论(0编辑  收藏  举报