视图中每列的源列是什么

时间:2017-10-24 21:08:29

标签: sql sql-server-2012 views metadata database-metadata

我如何知道视图中的每个列,或者源列列的过程 例如, 我有这张桌子:

CREATE TABLE [dbo].[tbl_Address](
    [iAddressId] [int] IDENTITY(1,1) NOT NULL,
    [nvStreet] [nvarchar](50) NULL,
    [iHouseNum] [int] NULL,
    [nvEnterance] [nvarchar](10) NULL,
    [iFloor] [int] NULL,
    [nvNeighberwood] [nvarchar](20) NULL,
    [nvCity] [nvarchar](20) NULL,
    [nvNote] [nvarchar](50) NULL,
 CONSTRAINT [PK_tbl_Address] PRIMARY KEY CLUSTERED 
(
    [iAddressId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

这个观点:

CREATE VIEW ViewALIAS
AS
SELECT a.nvStreet myStreet,a.nvCity manyStreeats FROM tbl_Address a  

所需答案:

nameObject | nameColumn | SourceObject | SourceColumn  
----------------------------------------------------- 
tbl_Address| nvStreet   | ViewALIAS    | myStreet  
tbl_Address| nvCity     | ViewALIAS    | manyStreeats

我知道如何制作列:nameObjectnameColumnSourceObject 或表:nameObjectSourceObjectSourceColumn
但我不知道如何匹配x和t

1 个答案:

答案 0 :(得分:0)

我认为你无法得到你想要的东西(见下面的解释)但你可以得到一个近似值,首先你可以使用以下方法得到视图的所有列:

select name, column_id from sys.columns where object_id=object_id('ViewALIAS')

然后您可以使用column dependencies获取视图引用的列,请注意这包括查询的任何部分中使用的所有列,而不仅是选择列表中的列(例如,它将列出一个WHERE条件中使用的列:

select dependencies.referenced_entity_name as referenced_name,
  entities.referenced_minor_id as column_id, entities.referenced_minor_name as column_name
from sys.sql_expression_dependencies as dependencies
join sys.objects as objects on object_id=referencing_id
join sys.schemas as schemas on schemas.schema_id=objects.schema_id
cross apply sys.dm_sql_referenced_entities(schemas.name+'.'+objects.name,'OBJECT') as entities
where entities.referenced_entity_name=dependencies.referenced_entity_name
  and (is_schema_bound_reference=0 or entities.referenced_minor_id=dependencies.referenced_minor_id)
  and entities.referenced_minor_id!=0
  and referencing_id=object_id('ViewALIAS')


你无法链接这两个结果,因为据我所知,在SQL Server中无法获得object catalog views中视图列和引用列之间的关系,我不知道具体原因但是我我确信主要原因是视图列几乎可以是任何东西,因此并不总是可以将它与表列匹配,例如:

CREATE VIEW ExampleView AS
SELECT ID, -- table column
  (Value1+Value2)*Value3 as Total, -- multiple columns
  12345 as Value, -- literal value
  getdate() as CurrentDate, -- scalar function
  dbo.fnMyFunction(Value1,Value2) as ScalarColumn, -- scalar function with parameters
  TableFunctionColumn, -- column from a table function (which can be almost anything)
  CASE WHEN Value1<10000 THEN Value2
    WHEN Value1>20000 THEN Value3
    ELSE Value2+Value3 END AS CaseColumn, -- different columns based on another value
  (SELECT SUM(OtherValue) FROM OtherTable
    WHERE OtherID=ID GROUP BY OtherValue) AS SubqueryColumn -- subquery result
FROM ExampleTable
CROSS APPLY dbo.fnTableFunction(ID)

我认为CASE列是最具代表性的示例,因为视图列使用的表列取决于另一个列的值,该列不直接用于列值。