什么时候以及为什么有些人决定他们需要在他们的数据库中创建一个视图?为什么不运行一个普通的存储过程或选择?


当前回答

下面是如何使用视图以及权限来限制用户可以在表中更新的列。

/* This creates the view, limiting user to only 2 columns from MyTestTable */
CREATE VIEW dbo.myTESTview 
WITH SCHEMABINDING AS
SELECT ID, Quantity FROM dbo.MyTestTable;

/* This uses the view to execute an update on the table MyTestTable */
UPDATE dbo.myTESTview
SET Quantity = 7
WHERE ID = 1

其他回答

在其他方面,它可以用于安全。如果您有一个“customer”表,您可能希望让所有销售人员访问名称、地址、邮政编码等字段,但不允许credit_card_number。您可以创建一个只包含他们需要访问的列的视图,然后授予他们对视图的访问权。

视图是查询的封装。转换为视图的查询往往比较复杂,因此将它们保存为视图以供重用是有好处的。

我通常创建视图来反规范化和/或聚合经常用于报告目的的数据。

EDIT

By way of elaboration, if I were to have a database in which some of the entities were person, company, role, owner type, order, order detail, address and phone, where the person table stored both employees and contacts and the address and phone tables stored phone numbers for both persons and companies, and the development team were tasked with generating reports (or making reporting data accessible to non-developers) such as sales by employee, or sales by customer, or sales by region, sales by month, customers by state, etc I would create a set of views that de-normalized the relationships between the database entities so that a more integrated view (no pun intended) of the real world entities was available. Some of the benefits could include:

减少编写查询时的冗余 建立关联实体的标准 提供机会 评估和最大化绩效 用于复杂的计算和连接 (例如在Schemabound视图上建立索引 在该软件中) 让数据更容易获取 对于团队成员和非开发人员来说是直观的。

这样做的原因不止一个。有时可以使通用连接查询变得简单,因为可以只查询表名而不是执行所有的连接。

另一个原因是将数据限制为不同的用户。例如:

表1:列- USER_ID;用户名;SSN

管理用户可以在实际表上有私权,但你不想访问的用户,比如SSN,你创建一个视图

CREATE VIEW USERNAMES AS SELECT user_id, username FROM Table1;

然后给他们访问视图而不是表的私权。

以下是两个常见的原因:

你可以用它来保证安全。在主表上不授予权限,创建限制列或行访问的视图,并向用户授予查看视图的权限。

你可以为了方便使用它。将视图中经常使用的一些表连接在一起。这可以使查询保持一致并更容易。