All we need is an easy explanation of the problem, so here it is.
I’m looking for a way to obtain system names of columns returned by an arbitrary sql query using Sql Server 2019. Here are a few sample queries and desired results:
company: id, name
employee: id, name, companyId
select * from company
| tableName | columnName |
company id
company name
select id as whatever from company
| tableName | columnName |
company id
select e.id, e.name, c.name from employee e join company c on e.companyId = c.id
| tableName | columnName |
employee id
employee name
company name
I’m not in control of the input queries, they are provided by end users.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
The sys.dm_exec_describe_first_result_set DMF returns column meta-data for the specified query, including additional information about the source column when @include_browse_information = 1
(the third parameter) is specified:
SELECT
source_schema AS tableSchema
, source_table AS tableName
, source_column AS columnName
FROM sys.dm_exec_describe_first_result_set(N'select * from company;',NULL,1);
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0