Find the real column name of an alias used in a view?

前端 未结 4 628
野性不改
野性不改 2020-11-30 13:00

Suppose I have a view in which some of the column names are aliases, like \"surName\" in this example:

CREATE VIEW myView AS
    SELECT  
            firstNa         


        
4条回答
  •  萌比男神i
    2020-11-30 13:17

    Having spent a number of hours trying to find an answer to this, and repeatedly running into solutions that didn't work and posters that appeared to eventually give up, I eventually stumbled across an answer here that appears to work:

    https://social.msdn.microsoft.com/Forums/windowsserver/en-US/afa2ed2b-62de-4a5e-ae70-942e75f887a1/find-out-original-columns-name-when-used-in-a-view-with-alias?forum=transactsql

    The following SQL returns, I believe, exactly what you're looking for, it's certainly doing what I need and appears to perform well too.

    SELECT  name
        , source_database
        , source_schema
        , source_table
        , source_column
        , system_type_name
        , is_identity_column
    FROM    sys.dm_exec_describe_first_result_set (N'SELECT * from ViewName', null, 1) 
    

    Documentation on the sys.dm_exec_describe_first_result_set function can be found here, it's available in SQL Server 2012 and later:

    https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-describe-first-result-set-transact-sql

    Full credit to the poster on the link, I didn't work this out myself, but I wanted to post this here in case it's useful to anyone else searching for this information as I found this thread much more easily than the one I linked to.

提交回复
热议问题