How to get column names from a query in SQL Server

Using SQL Server I have a very extensive request, with aliasing, etc. Is there a way using only SQL (a stored process is good, but not php, etc.) to get a list of all column names from this query? (I understand that I will probably have to include my request inside this solution, but this is normal. Just a temporary measure.)

Thank!

+4
source share
3 answers

If you are using SQL Server 2012 or later, you can use sys.dm_exec_describe_first_result_set

SELECT name 
FROM 
sys.dm_exec_describe_first_result_set
('Your Query Here', NULL, 0) ;

Demo

+8
source

This is too long for comment.

There are various ways to output columns from a query, for example:

select top 0 s.*
from (<your query here>) s;

.

. , , :

select top 0 s.*
into _TempTableForColumns
from (<your query here>) s;

information_schema ( , ):

select *
from information_schema.columns
where table_name = '_TempTableForColumns' and schema_name = 'dbo';

drop table _TempTableForColumns;

, . , , . , , , .

+4

After SQL Server 2008

select * 
from sys.columns c 
inner join sys.objects o on c.object_id = o.object_id 
where o.name = 'TableName'

Before

select * 
from syscolumns c 
inner join sysobjects o on c.id = o.id 
where o.name = 'TableName'
0
source

All Articles