建立&修改视图

一、建立视图

IF OBJECT_ID('Sales.OrderTotalsByYear', 'V') IS NOT NULL
    DROP VIEW Sales.OrderTotalsByYear;
GO

例一:

CREATE VIEW Sales.OrderTotalsByYear
WITH SCHEMABINDING ,  --在修改用于生成当前视图的表或视图时,一旦对当前视图产生影响(导致视图失效),则不允许修改。   
     ENCRYPTION  --加密,不能编辑(加密等级并不高)
AS
    SELECT  YEAR(O.orderdate) AS orderyear ,
            SUM(OD.qty) AS qty
    FROM    Sales.Orders AS O
            JOIN Sales.OrderDetails AS OD ON OD.orderid = O.orderid
    GROUP BY YEAR(orderdate);
GO

 

例二:

CREATE VIEW dbo.viewTestIndexInfo
AS
    SELECT DISTINCT
            Employees.*
    FROM    Employees
            JOIN Sales ON Employees.EmployeeID = Sales.EmployeeID
    WHERE   Title = 'Sales Person'
WITH CHECK OPTION   --如过视图中有where语句,通过view来修改表格的时候有可能更新掉 where条件之外的行,该选项用来强制更改的内容必须匹配where条件

二、查看数据库内的视图

--To explore view metadata using T-SQL, you can query the sys.views catalog view:
USE TSQL2012;
GO
SELECT name, object_id, principal_id, schema_id, type 
FROM sys.views;

--You can also query the INFORMATION_SCHEMA.TABLES system view, but it is slightly more complex:
SELECT SCHEMA_NAME, TABLE_NAME, TABLE_TYPE 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'VIEW';

三、修改视图

ALTER VIEW Sales.OrderTotalsByYear
WITH SCHEMABINDING
AS
    SELECT  O.shipregion ,
            YEAR(O.orderdate) AS orderyear ,
            SUM(OD.qty) AS qty
    FROM    Sales.Orders AS O
            JOIN Sales.OrderDetails AS OD ON OD.orderid = O.orderid
    GROUP BY YEAR(orderdate) ,
            O.shipregion;
GO

四、通过视图修改记录

--通过视图增加记录  如果视图带了CHECK OPTION 选项,那么插入的数据必须跟随WHERE条件
INSERT  vEmployees
        SELECT  3 ,
                'xxx' ,
                'xx'

转载于:https://www.cnblogs.com/haseo/p/view.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值