HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

System names of returned columns

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
returnedsystemcolumnsnames

Problem

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.

Solution

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);

Code Snippets

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);

Context

StackExchange Database Administrators Q#295406, answer score: 4

Revisions (0)

No revisions yet.