sql >> Base de Datos >  >> RDS >> Sqlserver

¿Pivotar fila dinámica a columna con parámetro de salida?

Puedes hacerlo de la siguiente manera:

CONSULTA

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

EJECUCIÓN

Exec sp_test 1

CONSULTA CON DATOS DE MUESTRA

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

SALIDA

Users   DIVISION    COMPANY
User1   050         1
User1   010         NULL