Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column names from a query in SQL Server

Using SQL Server.

I have a very extensive query, with a lot of aliasing, etc...

Is there a way, using just SQL (stored proc is fine, but not PHP, etc), to get a list of all column names from this query? (I realize I will have to probably embed my query inside of this solution but that is fine. Just a temporary measure.)

Thanks!

like image 602
WebDevGuy2 Avatar asked Jul 08 '15 16:07

WebDevGuy2


People also ask

Which query can be used to retrieve the column name?

We can verify the data in the table using the SELECT query as below. We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information.

How do I get column names and data types in SQL?

You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.


2 Answers

If you're using SQL Server 2012 or later you can take advantage of sys.dm_exec_describe_first_result_set

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

DEMO

like image 123
Conrad Frix Avatar answered Sep 20 '22 08:09

Conrad Frix


There are various ways that you can get the columns out of the query, such as:

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

Then you can parse the results.

However, I have found another approach useful. Create either a view or a table using the same logic:

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

Then use information_schema (or the system tables if you prefer):

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

drop table _TempTableForColumns;

The advantage of this approach is that you can get type information along with the column names. But the engine still has to run the query and that might take time even though no rows are returned. Although the column names and types are available after compiling, I am not aware of a way to get them without also executing the query.

like image 32
Gordon Linoff Avatar answered Sep 22 '22 08:09

Gordon Linoff