简体   繁体   English

Oracle plsql 触发器

[英]Oracle plsql trigger

How do I only allow a user to insert a row into a relational table only once a day?如何只允许用户每天只在关系表中插入一行?

CREATE OR REPLACE TRIGGER trigger_name
BEFORE INSERT ON Table_name
declare date[type?]
count int := 0;
BEGIN
if(00:00 to sysdate)
END IF
END

Why use a trigger when you can use a constraint?既然可以使用约束,为什么还要使用触发器?

create table t (
  c1       int,
  ins_date date default sysdate,
  ins_day  date as ( trunc ( ins_date ) ),
  constraint one_per_day unique ( ins_day )
);

insert into t ( c1 )
  values ( 1 );

insert into t ( c1 )
  values ( 2 );

ORA-00001: unique constraint (CHRIS.ONE_PER_DAY) violated

select * from t;

C1    INS_DATE              INS_DAY                
    1 07-NOV-2019 09:31:14  07-NOV-2019 00:00:00 

@ChrisSaxon has the correct idea of creating a constraint instead of trying a trigger. @ChrisSaxon 具有创建约束而不是尝试触发器的正确想法。 Not only is it cleaner it'll work, whereas a trigger will NOT work (cleanly anyway).它不仅更干净,而且可以工作,而触发器则无法工作(无论如何都是干净的)。 Any trigger attempting to enforce this would of necessity need to select from the same table resulting in a mutating table exception (ora-04091) or would need to be a:( compound trigger:(. But we can take Chris' suggestion a step further. Make the column ins_day a virtual column. Also as you indicated "allow a user to insert a row into a relational table only once a day" implies you can have multiple entries per day, just not by the same user. Incorporating these then we arrive at:任何试图强制执行此操作的触发器都必须需要 select 从同一个表中导致变异表异常 (ora-04091) 或者需要是:( 复合触发器:(。但我们可以更进一步地采取 Chris 的建议. 使列 ins_day 成为虚拟列。此外,正如您所指出的“允许用户每天仅在关系表中插入一行”意味着您每天可以有多个条目,但不能由同一个用户输入。合并这些然后我们到达:

create table test_1per_user_day (
  t1pd_id  integer,
  user_id  integer,
  ins_date date default sysdate,
  vir_1per_day  date GENERATED ALWAYS AS (trunc(ins_date)), 
  constraint t1d_one_per_day unique (user_id, vir_1per_day )
);

-- test run individually and stlect * from test_1per_day after each 
alter session set nls_date_format = 'yyyy-mm-dd hh24:mi:ss';
insert into test_1day(t1pd_id, user_id) values (1,1);
insert into test_1day(t1pd_id, user_id, ins_date) values (1,1, sysdate-2);
insert into test_1day(t1pd_id, user_id, ins_date,vir_1per_day) values (1,1, sysdate-1,sysdate);
insert into test_1day(t1pd_id, user_id) values (2,2);
insert into test_1day(t1pd_id, user_id) values (2,2);
update test_1day set vir_1per_day = sysdate; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM