Sqlserver中的视图

一、视图的基本知识

  什么是视图:视图是从一个或多个表导出的虚拟的表,具有普通表的结构,物理上是不存在的。视图是动态的数据的集合,数据是随着基表的更新而更新。
  视图的优点:  
     ①在多表查询时,查询方便。
     ②安全,用户只能查询和修改视图中有的字段(如一个视图只展示了用户表中的userName和ID,我们不能通过这个视图来修改用户表中的UserPass)。
  视图的缺点:
    性能不好,查询和修改时都要转化为对基表的操作。

  视图的应用:
    单表视图的update、delete、insert,会改变基本表的数据。(可以执行Insert操作,但是要保证视图中没有展示的列有默认值或可空,所以不建议使用视图来进行Insert操作)

    多表视图一般用于查询,可以进行update操作。sqlserver中不能进行删除操作(执行删除时如下图报错)

二、视图的使用

2.1  准备测试数据

--用户表
create table UserInfo(
    uId int identity(1,1) primary key,
    UserName nvarchar (20) not null,
    RoleId int not null 
)
--角色表
create table RoleInfo(
    rId int identity(1,1)  primary key,
    RoleName nvarchar(20)
)
--添加用户
insert into UserInfo values('user1',1)
insert into UserInfo values('user2',1)
insert into UserInfo values('user3',1)
insert into UserInfo values('user4',1)
insert into UserInfo values('user5',2)
insert into UserInfo values('user6',2)
--添加角色
insert into roleinfo values('管理员')
insert into roleinfo Values('一般用户')

2.2  使用视图

-----------------单表视图
--创建单表视图
create view v_users 
as 
select username,roleid from UserInfo

--使用单表视图
delete from v_users where username='user6' --基表中的记录被删除
update v_users set roleid=2   where username='user1' --基表中的记录被修改
--可以执行添加操作,但是要保证视图中没有的列有默认值或者可空(不建议)
drop view v_users--删除视图


------------------多表视图
create view v_userRole 
as
select username,rolename from userinfo,roleinfo where userinfo.roleid=roleinfo.rid

--使用多表视图
select * from v_userRole --查询
delete from v_userRole where username='user5' --删除时报错
update v_userRole set rolename='newRoleName' where username='user5' --修改,基表RoleInfo中的数据被修改

drop view v_userRole 

总结:视图用于复杂多表查询,作用是简化查询操作;用于修改,作用是不让用户修改未展示的列,保证安全性。不建议用视图来添加和删除。

 
原文地址:https://www.cnblogs.com/wyy1234/p/9042017.html