PostgreSQL包含check-option可更新視圖

一、創(chuàng)建可更新視圖:
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;

更新視圖插入數(shù)據(jù):
insert into usa_city (city,country_id )values ('Birmingham', 102);
結(jié)果:插入成功,但是此插入的結(jié)果并不在視圖usa_city中
插入的新行在視圖中不可見。這可能會(huì)造成安全問題,為防止用戶插入或更新通過視圖不可見的行,在創(chuàng)建視圖時(shí)可使用 
WITH CHECK OPTION 子句。



二、創(chuàng)建有檢查項(xiàng)的可更新視圖
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;
    

更新視圖插入數(shù)據(jù):
insert into usa_city (city,country_id )values ('Birmingham', 102);
結(jié)果:> 錯(cuò)誤:  新行違反了視圖"usa_city"的檢查選項(xiàng)

insert into usa_city (city,country_id )values ('Birenc', 103);
結(jié)果:插入成功,且只允許插入的數(shù)據(jù)滿足原視圖的where條件



三、檢查項(xiàng)含local的可更新視圖
(1)、創(chuàng)建一個(gè)可更新的基表視圖
create or replace view usa_a as 
    select city_id,city,country_id 
         from city 
     where city like 'A%';

(2)、創(chuàng)建檢查項(xiàng)含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;
        
        
更新視圖插入數(shù)據(jù):
insert into usa_a_city(city,country_id)values('Mirmin', 103);
結(jié)果:插入成功,因?yàn)閡sa_a_city視圖只需要檢查自身的插入數(shù)據(jù)是否滿足where條件即可

insert into usa_a_city(city,country_id)values('Mirmin', 102);
結(jié)果:插入失敗,> 錯(cuò)誤:  新行違反了視圖"usa_a_city"的檢查選項(xiàng)



(3)、創(chuàng)建檢查項(xiàng)含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;
        
更新視圖插入數(shù)據(jù):
insert into usa_a_city(city,country_id)values('Meery', 103);
結(jié)果:插入失敗,> 錯(cuò)誤:  新行違反了視圖"usa_a"的檢查選項(xiàng)
因?yàn)閡sa_a_city視圖使用了cascaded級(jí)聯(lián)檢查,即本身的where條件要滿足同時(shí)也要滿足基表視圖的where條件


insert into usa_a_city(city,country_id)values('Aeery', 103);
結(jié)果:插入成功,同時(shí)滿足了本身視圖的where條件,也滿足了基表視圖usa_a的where條件
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容