sql >> Database teknologi >  >> RDS >> Sqlserver

Drej dynamisk række til kolonne med outputparameter?

Du kan gøre det i følgende:

QUERY

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

UDFØRELSE

Exec sp_test 1

SØG MED EKSEMPEL DATA

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

OUTPUT

Users   DIVISION    COMPANY
User1   050         1
User1   010         NULL



  1. hvilken forespørgsel skal vi bruge til at opdele 1colmnn i flere kolonner

  2. Hvordan viser man data fra databasen?

  3. PostgreSQL-trigger returnerer ikke noget

  4. Konverter CASE-udtryk i SQL til afledt kolonne i SSIS