Get Select Column names from dynamic query in SQL Server

怎甘沉沦 提交于 2020-01-03 17:36:47

问题


If I have a random query, and would like to return the column names from this query:

SELECT 1 ONE, 2 TWO, 'THREE' THREE

How can I return the column names? Maybe even the column data type as well.

I can do this in c#, but I am looking for a way to do this all purely inside of Ms Sql.

Is this possible, if so how?

Would I have to create a temporary table, then check the info schema table? Or can I do it another way?


回答1:


You can use sp_describe_first_result_set to describe the columns returned from an arbitrary SQL statement. For example:

EXEC sp_describe_first_result_set @tsql = 'SELECT 1 ONE, 2 TWO, ''THREE'' THREE'

You will get results like this fiddle.

For older versions of SQL Server, you can also look at SET FMTONLY ON.



来源:https://stackoverflow.com/questions/36255470/get-select-column-names-from-dynamic-query-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!