SQLServer 行转列

DECLARE @cmd NVARCHAR(MAX);
DECLARE @names NVARCHAR(MAX);

SET @names = STUFF(( SELECT ‘,‘ + Name
                     FROM   dbo.ProposedProjectSettings
                     WHERE  ProposedProjectID = ‘100012‘
                   FOR
                     XML PATH(‘‘)
                   ), 1, 1, ‘‘);
SET @cmd = ‘
SELECT  *
FROM    ( SELECT    Name ,
                    Value
          FROM      dbo.ProposedProjectSettings
          WHERE     ProposedProjectID = ‘‘100012‘‘
        ) p PIVOT( MIN(Value) FOR Name IN ( ‘+@names+‘ ) )
AS pvt;‘;

EXEC(@cmd)

转置前
SQLServer 行转列

转置后
SQLServer 行转列

SQLServer 行转列

上一篇:还在写大量 if 来判断?试试用一个规则执行器来替代它


下一篇:如何使用反射获取类对象