介绍 (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

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
ASSELECT DISTINCT Employees.*FROM EmployeesJOIN 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

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;
GOINSERT 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部分​​,它应该返回以下内容:

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:

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

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

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中的任何其他对象一样,视图也具有属性。 在对象资源管理器中 ,右键单击要查看其属性的任何视图,然后选择“ 属性”

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 架构绑定 –指定视图是否绑定架构
  • For detailed information about view’s definition and properties, see Get Information About a View
  • 有关视图的定义和属性的详细信息,请参阅 获取 有关视图的 信息。

结论 (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/

创建视图SQL:在SQL Server中创建视图相关推荐

  1. sql server中创建链接服务器图解教程

    转自sql server中创建链接服务器图解教程 1.展开服务器对象-->链接服务器-->右击"新建链接服务器" 注意:必须以数据库管理员身份登录(通常也就是sa帐号) ...

  2. sql server中创建数据库和表的语法

    下面是sql server中创建数据库,创建数据表以及添加约束的sql语句: use master --创建数据库 if exists (select * from sysdatabases wher ...

  3. 细说Sql Server中的视图(下)转载

    原文:细说Sql Server中的视图(下)http://www.cnblogs.com/xbf321/archive/2009/06/19/view_two_in_sqlserver.html 1, ...

  4. CREATE VIEW SQL:通过SQL Server中的视图插入数据

    This is the third article in a series of learning the CREATE VIEW SQL statement. So far, I'd say tha ...

  5. weblogic中数据源_如何在WebLogic Server中创建MySQL数据源

    weblogic中数据源 使用应用程序服务器的一件很酷的事情是,它允许您在应用程序外部创建DataSource,并且可以与线程池和事务管理器等一起管理它.对于WebLogic Server,它附带了许 ...

  6. 如何在WebLogic Server中创建MySQL数据源

    使用应用程序服务器的一个很酷的事情是,它允许您在应用程序外部创建DataSource,并且可以与线程池和事务管理器等一起管理它.对于WebLogic Server,它附带了许多内置的JDBC驱动程序, ...

  7. 如何在SQL Server中创建视图

    In this article, we will learn the basics of the view concept in SQL Server and then explore methods ...

  8. 如何在SQL Server中创建SQL依赖关系图

    Deleting or changing objects may affect other database objects like views or procedures that depends ...

  9. 在SQL Server中创建用户角色及授权

    参考文献 http://database.51cto.com/art/201009/224075.htm 正文 要想成功访问 SQL Server 数据库中的数据, 我们需要两个方面的授权: 获得准许 ...

最新文章

  1. 面试题必问: 遇到过线上问题没,你是怎么排查的?
  2. 如何用python创建一个下载网站-用Python写一个简单的网页下载
  3. 配置kubernetes服务basic auth
  4. CSS清除默认样式,看完这篇彻底明白了
  5. 三包围结构的字是什么样的_一年级语文重点(字、字母、字词、词语、句子)知识点汇总!...
  6. 真正的门槛 - 全干工程师
  7. Maya+3dsMax三维建模
  8. php删除树结构文件,树型结构列出目录中所有文件的php代码
  9. LAN to LAN IPSEC ××× 的配置报告
  10. vue-cli 2.x 项目优化之:引入本地静态库文件
  11. jeDate日期控件 时间最大值最小值禁用的bug修改
  12. 【剑指Offer(专项突击版)】001~059题目题解汇总
  13. 英特尔边缘软件中心介绍
  14. 数据库常用增删改查语句
  15. 微信小程序服务通知模板的实现
  16. 在iOS设备上进行抓包(补充)
  17. vs2008 html5 的安装,vs2008安装教程,详细教您vs2008安装教程
  18. html 字体样式斜体,CSS font-style斜体字体倾斜体样式
  19. java 简单文件加密
  20. 主语从句、宾语从句、表语从句、同位语从句

热门文章

  1. 安装 webpack 的各种方法
  2. pertII型管和pertI型管的区别
  3. GBase8s数据库EXECUTE PROCEDURE 语句
  4. 手机视频硬解码和软解码的区别
  5. pytorch-unsqueeze用法
  6. Linux学习笔记3(虚拟机安装ubuntu文件传输远程连接和控制)
  7. PS 学习笔记 14-历史记录画笔工具组
  8. 公众号跳转小程序的4个简单方法实现
  9. 吃鸡2019年5月7日服务器维护,时隔6个月,“吃鸡”玩家打开《全军出击》,天美发来熟悉的提示...
  10. HTML <b>加粗与<strong>加粗标签区别