Select Columns of a View

家住魔仙堡 提交于 2019-12-04 16:14:41

问题


I'm attempting to select the column names of a view in a similar way as selecting from information_schema.columns.

I can't seem to find a way to do this. Has anyone else done this before or know if it is even possible?


回答1:


information_schema.columns.Table_name (at least under Sql Server 2000) includes views, so just use

SELECT * FROM information_schema.columns WHERE table_name = 'VIEW_NAME'



回答2:


Try this:

SELECT *
FROM sys.views

This gives you the views as such - if you need the columns, use this:

SELECT * 
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.YourViewNameHere')

Not sure how you can do it using the INFORMATION_SCHEMA - I never use that, since it feels rather "clunky" and unintuitive, compared to the sys schema catalog views.

See the MSDN docs on the Catalog Views for all the details of all the views available, and what information they might contain.




回答3:


INFORMATION_SCHEMA views holds metadata about objects within database. INFORMATION_SCHEMA.COLUMNS uses underlying sys tables to retrive the metadata ( check sp_helptext 'master.Information_schema.columns' ). You can use this simpler query to select column names used in any view.

SELECT col.name 
FROM <db_name>.sys.columns col, <db_name>.sys.views vew
WHERE col.object_id = vew.object_id
AND vew.name = '<view_name>'



回答4:


SELECT distinct VIEW_NAME
  ,TABLE_SCHEMA
  ,TABLE_NAME
  ,COLUMN_NAME
FROM   INFORMATION_SCHEMA.VIEW_COLUMN_USAGE
--WHERE  TABLE_SCHEMA = 'Person'
ORDER BY
   VIEW_NAME
  ,TABLE_SCHEMA
  ,TABLE_NAME
  ,COLUMN_NAME



回答5:


I found this way working for views (SQL 2017). I was not able to get data from information_schema.columns and sys.columns:

    SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('<view_name>')


来源:https://stackoverflow.com/questions/11268403/select-columns-of-a-view

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