PostgreSQL包含check-option可更新视图

一、创建可更新视图:
create or replace view usa_city as
    select city_id,city,country_id 
         from city
    where country_id=103 order by city;
    
select * from usa_city;

更新视图插入数据:
insert into usa_city (city,country_id )values ('Birmingham', 102);
结果:插入成功,但是此插入的结果并不在视图usa_city中
插入的新行在视图中不可见。这可能会造成安全问题,为防止用户插入或更新通过视图不可见的行,在创建视图时可使用 
WITH CHECK OPTION 子句。



二、创建有检查项的可更新视图
create or replace view usa_city as
    select city_id,city,country_id 
         from city
    where country_id=103 order by city
    with check option;
    

更新视图插入数据:
insert into usa_city (city,country_id )values ('Birmingham', 102);
结果:> 错误:  新行违反了视图"usa_city"的检查选项

insert into usa_city (city,country_id )values ('Birenc', 103);
结果:插入成功,且只允许插入的数据满足原视图的where条件



三、检查项含local的可更新视图
(1)、创建一个可更新的基表视图
create or replace view usa_a as 
    select city_id,city,country_id 
         from city 
     where city like 'A%';

(2)、创建检查项含local的可更新视图
create or replace view usa_a_city as 
    select city_id,city,country_id 
         from usa_a
    where country_id=103 order by city
    with local check option;
        
        
更新视图插入数据:
insert into usa_a_city(city,country_id)values('Mirmin', 103);
结果:插入成功,因为usa_a_city视图只需要检查自身的插入数据是否满足where条件即可

insert into usa_a_city(city,country_id)values('Mirmin', 102);
结果:插入失败,> 错误:  新行违反了视图"usa_a_city"的检查选项



(3)、创建检查项含cascaded的可更新视图
create or replace view usa_a_city as 
    select city_id,city,country_id 
         from usa_a
    where country_id=103 order by city
    with cascaded check option;
        
更新视图插入数据:
insert into usa_a_city(city,country_id)values('Meery', 103);
结果:插入失败,> 错误:  新行违反了视图"usa_a"的检查选项
因为usa_a_city视图使用了cascaded级联检查,即本身的where条件要满足同时也要满足基表视图的where条件


insert into usa_a_city(city,country_id)values('Aeery', 103);
结果:插入成功,同时满足了本身视图的where条件,也满足了基表视图usa_a的where条件
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容