简体   繁体   中英

Get column names from select query in SQL Server

I have a select in SQL Server like this:

Select name, email, username, tel 
from ViewName

I want to get a list of column names from that select.

Note :

1. I don't have table name

2. Select query is dynamic

Select query is in view

Try This:

I hope this will work dynamically, it'll select all the columns depending on the Table_View_Name you passed in the parameter .

declare @tab varchar(max)='Your_Dynamic_Table_View_Name'
declare @txt varchar(max)='SELECT COLUMN_NAME FROM information_schema.columns WHERE table_name ='+@tab


declare @columns varchar(max)=(SELECT 
  STUFF((
    SELECT ', ' + COLUMN_NAME
    FROM information_schema.columns where table_name=@tab
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') AS NameValues)


exec('select '+@columns+' from '+@tab)

Try these..

sp_help 'viewName'

or

select c.* from syscolumns c inner join sysobjects o on o.id=c.id where o.name='viewName'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM