视图中每一列的源列是啥
Posted
技术标签:
【中文标题】视图中每一列的源列是啥【英文标题】:What is the source column of each column in view视图中每一列的源列是什么 【发布时间】:2017-10-24 21:08:29 【问题描述】:我如何知道视图中的每一列,或处理源列 例如, 我有这张桌子:
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
我知道如何制作列:nameObject
、nameColumn
、SourceObject
或表:nameObject
、SourceObject
、SourceColumn
但我不知道如何匹配 x 和 t
【问题讨论】:
必须为视图解析系统表源才能获取该数据。 为什么需要这样做? 我做一个插件 【参考方案1】:我认为你不能得到你想要的东西(见下面的解释),但你可以得到一个近似值,首先你可以使用以下方法获取视图的所有列:
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
列是最具代表性的例子,因为视图列使用的表列依赖于another列的值,而该列的值不直接用于列值。
【讨论】:
以上是关于视图中每一列的源列是啥的主要内容,如果未能解决你的问题,请参考以下文章
IP 地址(在源列下)在 AWS 安全组的入站和出站规则中代表/或含义是啥?