Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Pivot Dynamic row to Column com parâmetro de saída?


Você pode fazê-lo no seguinte:

PERGUNTA
CREATE PROCEDURE [dbo].[sp_test]
@AppPool AS NVARCHAR(60)
AS
DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += QUOTENAME([Name]) + ','
FROM   (SELECT DISTINCT Attribute as Name
        FROM    [dbo].[Vy_UserAccess]
        WHERE   PoolID = @AppPool
        ) a 
ORDER BY Name DESC 

SET @cols   = LEFT(@cols, LEN(@cols) - 1)   

SET @sql    = 'SELECT Users, ' + @cols + ' FROM 
    (
    SELECT [Pool],[Users],[RecNum],[Attribute],[Values] 
    FROM [dbo].[Vy_UserAccess]
     ) AS  T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'

EXEC sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool

EXECUÇÃO
Exec sp_test 1

CONSULTA COM DADOS DE AMOSTRA
CREATE PROCEDURE sp_test 
@AppPool AS NVARCHAR(60)
AS

CREATE TABLE #test
(
    PoolId NVARCHAR(60),
    Pool NVARCHAR(40),
    Users NVARCHAR(60),
    RecNum INT,
    Attribute NVARCHAR(40),
    [Values] NVARCHAR(20)
)
INSERT INTO #test VALUES
('1', 'FINANCE', 'User1', 2, 'DIVISION', '010'),
('1', 'FINANCE', 'User1', 1, 'COMPANY',  '1'),
('1', 'FINANCE', 'User1', 1, 'DIVISION', '050')



DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += QUOTENAME([Name]) + ','
FROM   (SELECT DISTINCT Attribute as Name
        FROM    #test
        WHERE   PoolID = @AppPool       
        ) a 
ORDER BY Name DESC                      
SET @cols   = LEFT(@cols, LEN(@cols) - 1)


SET @sql    = 'SELECT Users, ' + @cols + ' FROM 
    (
    SELECT [Pool],[Users],[RecNum],[Attribute],[Values] 
    FROM #test
     ) AS  T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'

EXEC Sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool

DROP TABLE #test

SAÍDA
Users   DIVISION    COMPANY
User1   050         1
User1   010         NULL