创建视图SQL:在SQL Server中创建视图

介绍 (Introduction)

In this article, we are going to see how to use the CREATE VIEW SQL statement to create a view. This is the first article in a series that will be a programmatical approach of creating, altering and working with views using T-SQL. If you are a beginner and you don’t even know what a view is, don’t worry. We will kick off with a definition, and then move on to some basics like syntax, examples, use cases, etc.

在本文中,我们将了解如何使用CREATE VIEW SQL语句创建视图。 这是本系列的第一篇文章,它将是使用T-SQL创建,更改和使用视图的编程方法。 如果您是初学者,甚至不知道视图是什么,请不要担心。 我们将从定义开始,然后继续一些基础知识,例如语法,示例,用例等。

A view is simply a virtual table. Think of it as just a query that is stored on SQL Server and when used by a user, it will look and act just like a table but it’s not. It is a view and does not have a definition or structure of a table. Its definition and structure is simply a query that, under the hood, can access many tables or a part of a table.

视图只是一个虚拟表。 可以将其视为仅存储在SQL Server上的查询,并且当用户使用它时,它的外观和作用就像表一样,但事实并非如此。 它是一个视图,没有表的定义或结构。 它的定义和结构只是一个查询,它可以在后台访问许多表或表的一部分。

Views can be used for a few reasons. Some of the main reasons are as follows:

出于某些原因,可以使用视图。 一些主要原因如下:

  • To simplify database structure to the individuals using it

    为了简化使用它的个人的数据库结构
  • As a security mechanism to DBAs for allowing users to access data without granting them permissions to directly access the underlying base tables

    作为DBA的安全机制,允许用户访问数据而无需授予他们直接访问基础基表的权限
  • To provide backward compatibility to applications that are using our database

    为了向后兼容使用我们数据库的应用程序

Having said that, those reasons are a topic for designing views which we will not touch in this series. In this article, we are going to go through the CREATE VIEW SQL syntax, see what views are all about, and what we can do with them.

话虽如此,这些原因是设计视图的主题,在本系列中我们将不作讨论。 在本文中,我们将介绍CREATE VIEW SQL语法,查看所有视图的含义以及如何使用它们。

句法 (Syntax)

CREATE  OR ALTER  VIEW  schema_name.view_name
WITH <view_attribute>
AS select_statement   
[WITH CHECK OPTION]

We all know how complicated syntax can get but this is not the case with views. A view can be created by saying CREATE VIEW followed by a name WITH view attributes:

我们都知道语法会变得多么复杂,但是视图却并非如此。 可以通过说出CREATE VIEW后跟一个具有WITH视图属性的名称来创建视图:

  • ENCRYPTION – Using this attribute prevents the view from being published as part of SQL Server replication 加密 –使用此属性可防止视图作为SQL Server复制的一部分发布
  • SCHEMABINDING – Binds the view to the schema of the underlying table. We will use this one in another article when indexing a view SCHEMABINDING –将视图绑定到基础表的架构。 索引视图时,我们将在另一篇文章中使用它
  • VIEW_METADATA – Causes SQL Server to return to the DB-Library, ODBC, and OLE DB APIs the metadata information about the view VIEW_METADATA –使SQL Server返回DB-Library,ODBC和OLE DB API有关视图的元数据信息

After the AS, it goes the actual SELECT statement that defines the query. This is usually the bulk of a query AKA the DML statement that is going to make the view and its results.

在AS之后,它将进入定义查询的实际SELECT语句。 这通常是查询(即要生成视图及其结果的DML语句)的大部分。

The WITH CHECK OPTION is very useful when inserting data through a view. When a row is modified through a view, this option gives us control over inserted data into the table that follows the WHERE clause in the view’s definition. More about this in the upcoming article.

通过视图插入数据时,WITH CHECK OPTION非常有用。 通过视图修改行时,此选项使我们可以控制插入到表中的数据,该数据紧随视图定义中的WHERE子句。 在即将到来的文章中对此有更多的了解。

CREATE VIEW SQL语句 (CREATE VIEW SQL statement)

Without further ado, let’s fire up SQL Server Management Studio and start working on views. Before we use the CREATE VIEW SQL statement, let’s create a new database from Object Explorer called SQLShackDB, and then create a few tables in it by running the script from below:

事不宜迟,让我们启动SQL Server Management Studio并开始处理视图。 在使用CREATE VIEW SQL语句之前,让我们从Object Explorer创建一个名为SQLShackDB 的新数据库 ,然后通过从下面运行该脚本在其中创建一些表:

CREATE TABLE Employees
(EmployeeID    INT NOT NULL, 
 FirstName     NVARCHAR(50) NOT NULL, 
 MiddleName    NVARCHAR(50) NULL, 
 LastName      NVARCHAR(75) NOT NULL, 
 Title         NVARCHAR(100) NULL, 
 HireDate      DATETIME NOT NULL, 
 VacationHours SMALLINT NOT NULL, 
 Salary        DECIMAL(19, 4) NOT NULL
);
GO
CREATE TABLE Products
(ProductID INT NOT NULL, 
 Name      NVARCHAR(255) NOT NULL, 
 Price     DECIMAL(19, 4) NOT NULL
);
GO
CREATE TABLE Sales
(SalesID    UNIQUEIDENTIFIER NOT NULL, 
 ProductID  INT NOT NULL, 
 EmployeeID INT NOT NULL, 
 Quantity   SMALLINT NOT NULL, 
 SaleDate   DATETIME NOT NULL
);
GO

T-SQL script for creating three sample tables in SQLShack database

Now, that we have our sample database with tables in it, we can create a view called vEmployeesWithSales using the script from below as an example:

现在,我们有了包含表的示例数据库,我们可以使用下面的脚本作为示例,创建一个名为vEmployeesWithSales的视图:

USE SQLShackDB;
GO
CREATE VIEW vEmployeesWithSales
AS
     SELECT DISTINCT 
            Employees.*
     FROM Employees
          JOIN Sales ON Employees.EmployeeID = Sales.EmployeeID;
GO

This is a simple view with a simple SELECT statement that returns a list of employees that have a sale. As a matter of fact, you can always test the query before creating the view by executing only the SELECT part of the CREATE VIEW SQL statement and it’s a good idea to see if the query will return something. Make sure that you are connected to the appropriate database first, then mark the SELECT part of the code, and hit Execute:

这是带有简单SELECT语句的简单视图,该语句返回具有销售记录的雇员的列表。 实际上,您始终可以通过仅执行CREATE VIEW SQL语句的SELECT部分​​来在创建视图之前测试查询,这是个好主意,看看查询是否会返回某些内容。 确保首先连接到适当的数据库,然后标记代码的SELECT部分​​,然后单击Execute

CREATE VIEW SQL script for creating a simple view

The query returns no result because we don’t actually have any data in our new tables, but you can see the list of columns that returned. The next thing we can do is insert some data into tables. To do this, use the following script:

该查询未返回任何结果,因为新表中实际上没有任何数据,但是您可以看到返回的列的列表。 我们可以做的下一件事是将一些数据插入表中。 为此,请使用以下脚本:

USE SQLShackDB;
GO
    
INSERT INTO Employees SELECT 1, 'Ken', NULL, 'Sánchez', 'Sales Representative', '1/1/2016', 2080, 45000;
INSERT INTO Employees SELECT 2, 'Janice', NULL, 'Galvin', 'Sales Representative', '12/11/2016', 2080, 45000;
    
INSERT INTO Products SELECT 1, 'Long-Sleeve Logo Jersey, S', 12.99;
INSERT INTO Products SELECT 2, 'Long-Sleeve Logo Jersey, M', 14.99;
INSERT INTO Products SELECT 3, 'Long-Sleeve Logo Jersey, L', 16.99;
INSERT INTO Products SELECT 4, 'Long-Sleeve Logo Jersey, XL', 18.99;
    
INSERT INTO Sales SELECT NEWID(), 1, 1, 4, '04/15/2016';
INSERT INTO Sales SELECT NEWID(), 2, 1, 1, '02/01/2016';
INSERT INTO Sales SELECT NEWID(), 3, 1, 2, '03/12/2016';
INSERT INTO Sales SELECT NEWID(), 2, 2, 2, '03/18/2016';
INSERT INTO Sales SELECT NEWID(), 3, 2, 1, '04/16/2016';
INSERT INTO Sales SELECT NEWID(), 4, 2, 2, '04/23/2016';

Just to make sure that data is inserted into our tables successfully, re-execute the SELECT part of the CREATE VIEW SQL statement and it should return the following:

为了确保将数据成功插入到我们的表中,请重新执行CREATE VIEW SQL语句的SELECT部分​​,它应该返回以下内容:

The results returned by SELECT part of the CREATE VIEW SQL script

Note that we are using the DISTINCT with SELECT to prevent the retrieval of duplicate records because both employees have multiple records.

请注意,由于两个雇员都有多个记录,因此我们将DISTINCT与SELECT一起使用以防止检索重复记录。

Let’s get back to our view and see how it looks in our database. If we head over to Object Explorer and expand the Views folder under our demo database, we will find our view that looks exactly like a table because it has columns in it:

让我们回到视图,看看它在数据库中的外观。 如果我们转到对象资源管理器并展开我们的演示数据库下的“ 视图”文件夹,我们会发现我们的视图看上去完全像一个表,因为其中包含列:

The view in Object Explorer as a result of a successfully executed CREATE VIEW SQL statement

These are all columns that this view will return. Let’s see what happens if we treat this view as a table. Write a SELECT statement but instead of saying select everything from and then the name of a table, we will simply say from a view:

这些都是该视图将返回的所有列。 让我们看看如果将此视图视为表格会发生什么。 编写SELECT语句,而不是说先从中选择所有内容,然后再选择表名,我们将仅从视图中说出:

SELECT * FROM vEmployeesWithSales

Results of a SELECT query using the view as the source

As can be seen from the figure above, the result is exactly the same as when querying data using actual tables.

从上图可以看出,结果与使用实际表查询数据时完全相同。

Like any other object in SQL Server, views have properties too. In Object Explorer, right-click any view of which you want to view the properties and select Properties:

像SQL Server中的任何其他对象一样,视图也具有属性。 在对象资源管理器中 ,右键单击要查看其属性的任何视图,然后选择“ 属性”

View properties window of a view in SQL Server Management Studio

Notice that here you can see the actual options that the view was created with to understand how its data is derived from the actual tables:

注意,在这里您可以看到创建视图的实际选项,以了解其数据是如何从实际表中派生的:

  • ANSI NULLs – It indicates if the object was created with the ANSI NULLs option ANSI NULL –指示是否使用ANSI NULLs选项创建对象
  • Encrypted – Specifies whether the view is encrypted 已加密 –指定视图是否已加密
  • Quoted identifier – Shows if the object was created with the quoted identifier option 带引号的标识符 –显示是否使用带引号的标识符选项创建对象
  • Schema bound – Designates whether the view is schema-bound 架构绑定 –指定视图是否绑定架构

结论 (Conclusion)

In this article, the goal was only to get familiar with the CREATE VIEW SQL statement syntax and creating a basic view. Moving on to a bit more complex stuff like creating a view with aggregates in it will be the focus in the next article. In other words, we are going to use the DLM language (Data Manipulation Language) and write some more advance SELECT queries.

在本文中,目标只是熟悉CREATE VIEW SQL语句语法并创建基本视图。 下一篇文章将重点介绍更复杂的内容,例如创建带有聚合的视图。 换句话说,我们将使用DLM语言(数据操作语言)并编写一些更高级的SELECT查询。

I hope this article on CREATE VIEW SQL statement has been informative for you and I thank you for reading it. Stay tuned for the next one…

我希望有关CREATE VIEW SQL语句的这篇文章对您有所帮助,也感谢您阅读本文。 请继续关注下一个…

目录 (Table of contents)

CREATE VIEW SQL: Creating views in SQL Server
CREATE VIEW SQL: Modifying views in SQL Server
CREATE VIEW SQL: Inserting data through views in SQL Server
CREATE VIEW SQL: Working with indexed views in SQL Server
创建视图SQL:在SQL Server中创建视图
创建视图SQL:在SQL Server中修改视图
CREATE VIEW SQL:通过SQL Server中的视图插入数据
CREATE VIEW SQL:在SQL Server中使用索引视图

翻译自: https://www.sqlshack.com/create-view-sql-creating-views-in-sql-server/

  • 9
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值