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


当前回答

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

/* 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

其他回答

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

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视图上建立索引 在该软件中) 让数据更容易获取 对于团队成员和非开发人员来说是直观的。

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

/* 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

关于视图的一件奇怪的事情是,它们被Microsoft Access视为表:当您使用ODBC将Microsoft Access前端附加到SQL数据库时,您将在可用表列表中看到表和视图。因此,如果你在MS Access中准备复杂的报告,你可以让SQL服务器来做连接和查询,这大大简化了你的工作。在Excel中准备查询也是如此。

在对遗留数据库进行报告时,视图可能是天赐之物。特别是,您可以使用有意义的表名,而不是神秘的字母名(其中两个字母是常见的前缀!),或者充满缩写的列名,我确信这在当时是有意义的。

以下是两个常见的原因:

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

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