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!
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
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With