问题
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