(二十二)视图

--(1)视图:视图就是一个虚拟的数据表,该数据表中的数据记录是有一条查询语句的查询结果得到的。
/*(2)创建视图准则;A、视图名称必须遵循标识符的规则,该名称不得与该架构的任何表的名称相同;
                     B、你可以对其它视图创建视图。允许嵌套视图,但嵌套不得超过32层。视图最多可以有1024个字段;
										 C、不能将规则和default定义于视图相关联;
										 D、视图的查询不能包含compute子句、compute by子句或into关键字;
										 E、定义视图的查询不能包含order by子句,除非在select语句的选择列中还有top子句;
	 (3)下列情况必须指定视图中每列的名称:
	                   A、视图中的任何列都是从算术表达式、内置函数或者常量派生而来;
										 B、视图中有两列或多列具有相同名称
										 (通常由于视图定义包含联结,因此来自两个或多个不同的列具有相同的名称)
										 C、希望视图中的列指定一个与其原列不同的名称(也可以在视图中重命名列)。
										 无论是否重命名,视图列都会继承原列的数据类型。*/
--1.创建视图
if(exists (select * from sys.objects where name='v_stu'))
   drop view v_stu 
go 
create view v_stu 
as 
select id,name,age,sex from studentB;	 

select * from v_stu;--查询视图

--2.修改视图
--方式一
alter view v_stu
as
select id, name,age,sex,cid from studentB;
 
select * from v_stu;--查询视图

--方式二
alter view v_stu(编号, 名称, 性别)
as
    select id, name, sex from studentB
go

select * from v_stu;--查询视图

select * from information_schema.views;--查询数据库中创建的视图
 
--3.加密视图
if(exists(select * from sys.objects where name='v_student_info'))
   drop view v_student_info
go 
create view v_student_info 
with encryption --加密
as 
   select id,name,age from studentB 
go 
--view_definition is null 
select * from information_schema.views where table_name like 'v_stu';	--未加密的视图可以查看视图的定义
select * from information_schema.views where table_name like 'v_student';		--已加密的视图无法查看视图的定义
exec sp_helptext 'v_student_info';	
select * from v_student_info;

--4.视图的访问方式
select * from studentB;--原始表
select * from Student;
--A:简单查询
select * from v_stu;
--B:连接视图与其他表(关联视图和表相同的字段进行查询)
select v.name,c.stuname from v_stu v join student c on v.id=c.stuid;
--C:更新通过视图修改基础表数据(需满足特定条件)
update v_stu set name='david',age=18,cid=34 where id=5;
--D:删除视图中的数据
delete from v_stu where name='david';
									

 

posted @ 2025-05-15 16:52  代号六零一  阅读(24)  评论(0)    收藏  举报