前面讲的两种类型的表表达式(派生表和CTE),它们的作用范围都非常有限,仅限于在单个语句范围内使用,只要包含这些表表达式的外部查询完成操作,它们便随它消失了。这也就意味着派生表和CTE都是不可重用的。
相较于派生表和CTE,视图是一种可重用的表表达式,它定义在数据库中。一旦创建,它就是数据库的永久部分,只有用删除命令显示删除它们才会从数据库中删除。下面是视图的示例代码。
USE TSQLFundamentals2008; GO -- 视图 -- 创建视图 IF OBJECT_ID('dbo.V_USACusts','V') IS NOT NULL DROP VIEW dbo.V_USACusts; GO CREATE VIEW dbo.V_USACusts AS SELECT custid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax FROM Sales.Customers WHERE country= N'USA'; GO -- 查询视图 SELECT custid,companyname,region FROM dbo.V_USACusts ORDER BY region; -- 修改视图 ALTER VIEW dbo.V_USACusts AS SELECT custid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax FROM Sales.Customers WHERE country= N'USA'; GO -- 查看视图定义(通过函数OBJECT_DEFINITION) SELECT OBJECT_DEFINITION(OBJECT_ID('dbo.V_USACusts','V')); EXEC sys.sp_helptext @objname = N'dbo.V_USACusts'; -- 修改视图,指定ENCRYPTION选项,可以对视图的定义进行混淆处理,这样普通用户无法查看 ALTER VIEW dbo.V_USACusts WITH ENCRYPTION AS SELECT custid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax FROM Sales.Customers WHERE country= N'USA'; GO -- 修改视图,指定SCHEMABINDING选项,可以防止被引用的对象或列被删除 ALTER VIEW dbo.V_USACusts WITH SCHEMABINDING AS SELECT custid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax FROM Sales.Customers WHERE country= N'USA'; GO -- 修改视图,指定CHECK OPTION选项,防止通过视图执行的数据修改与视图中设置的过滤条件发生冲突 ALTER VIEW dbo.V_USACusts AS SELECT custid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax FROM Sales.Customers WHERE country= N'USA' WITH CHECK OPTION; GO