Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Retrieve Column Headers of a Select Query?

How it is possible to retrieve column headers of a select query as a single column in SQL Server ? (it is preferred to retrieve data type of columns )

Query example:

select a.PartId, a.PartName, b.GroupName 
from Parts as a 
inner join Groups as b on a.GroupRef = b.GroupId

Expected result:

Columns 
--------
PartId
PartName
GroupName
like image 213
Behnam Avatar asked Feb 10 '23 01:02

Behnam


1 Answers

Starting from SQL Server 2012+ you can use sys.dm_exec_describe_first_result_set to get all metadata about result set:

DBFiddle Demo

DECLARE @tsql NVARCHAR(MAX) = 
  N'select a.PartId , a.PartName , b.GroupName 
from Parts as a inner join Groups as b 
on a.GroupRef = b.GroupId';

SELECT name AS [Columns]
FROM sys.dm_exec_describe_first_result_set(@tsql, NULL, 1)
like image 126
Lukasz Szozda Avatar answered Feb 11 '23 23:02

Lukasz Szozda