Sql-Server

返回列的系統名稱

  • July 8, 2021

我正在尋找一種方法來獲取使用 Sql Server 2019 的任意 sql 查詢返回的列的系統名稱。以下是一些範例查詢和所需的結果:

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

我無法控制輸入查詢,它們由最終使用者提供。

sys.dm_exec_describe_first_result_set DMF返回指定查詢的列元數據,包括指定(第三個參數)時有關源列的附加資訊@include_browse_information = 1

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

引用自:https://dba.stackexchange.com/questions/295406