2017-03-29 24 views
-1

我想創建行數有限的表格。 例如,如果我們嘗試將數據插入到rownumber大於2.000的表中,那會返回一些錯誤或其他信息。創建行數有限的表格

如何管理?

回答

1

一種方法可以通過創建一個觸發器來檢查插入行的數量;例如,假設你有此表

create table notManyRows(n number) 

,你想的行數限制爲3,你可以添加一個觸發條件:

create or replace trigger notManyRowsTrg 
after insert on notManyRows 
declare 
    vCheck number; 
begin 
    select count(*) 
    into vCheck 
    from notManyRows; 
    -- 
    if vCheck > 3 then 
     raise_application_error(-20001, 'Too many rows in the table'); 
    end if; 
end; 

它是如何工作的:

SQL> insert into notManyRows values (1); 

1 row created. 

SQL> insert into notManyRows values (1); 

1 row created. 

SQL> insert into notManyRows values (1); 

1 row created. 

SQL> insert into notManyRows values (1); 
insert into notManyRows values (1) 
* 
ERROR at line 1: 
ORA-20001: Too many rows in the table 
ORA-06512: at "ALEK.NOTMANYROWSTRG", line 9 
ORA-04088: error during execution of trigger 'ALEK.NOTMANYROWSTRG' 


SQL> 
+0

是否有可能創建主鍵,這將自動從數字1增加到2000? – Savke

+1

這取決於你的Oracle版本。但是,這怎麼能防止插入行?你仍然需要一個觸發器來檢查PK值是否大於極限值;另外,如果我在1 ... 19999中刪除所有帶有Ids的行,該怎麼辦? – Aleksej

+0

非常感謝。當有人解決它時,它看起來很容易:) – Savke