Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Dynamic Pivot Column Names

For the necessity of my application, I must return the column names of a query as the very first row. Now I must PIVOT this result in order to UNION it with my result set, but the difficult part is: it must be dynamic, so if I ever add new columns to this table, the SELECT will bring all the names pivoted.

The following SELECT brings me the Column names:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Codes'
ORDER BY INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION 

And my result set is:

COLUMN_NAME
Id
CodeName
Country
StartDate
EndDate 

What I expect is:

Id    CodeName    Country    StartDate    EndDate (... whatever other columns I might have)

Is there any easy way to do that without hardcoding the column names?

Thank you in advance!

like image 582
user3472897 Avatar asked Dec 22 '14 12:12

user3472897


2 Answers

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + COLUMN_NAME + ']', 
               '[' + COLUMN_NAME + ']')
               FROM    (SELECT DISTINCT COLUMN_NAME,INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION O 
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = 'CODES') PV  
               ORDER BY O


DECLARE @query NVARCHAR(MAX)
SET @query = '           
              SELECT TOP 0 * FROM 
             (
                 SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_NAME = ''CODES''
             ) x
             PIVOT 
             (
                 MIN(COLUMN_NAME)
                 FOR [COLUMN_NAME] IN (' + @cols + ')
            ) p    

            '     
EXEC SP_EXECUTESQL @query
like image 51
Sarath KS Avatar answered Dec 16 '22 10:12

Sarath KS


Starting with SQL Server 2017, there's a function for this: STRING_AGG. I used the QUOTENAME function as well here, to make adding the [ ] brackets easier.

DECLARE @ColumnNames NVARCHAR(MAX);
SELECT @ColumnNames = STRING_AGG(QUOTENAME(COLUMN_NAME), ',')
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME='Codes';
like image 36
Luc VdV Avatar answered Dec 16 '22 10:12

Luc VdV