SQL“对于每一行”未按预期工作/未正确使用

时间:2017-05-12 16:17:56

标签: sql postgresql plpgsql

编辑:它的工作很精细,我只是DUMB

我有以下触发器:

CREATE TRIGGER reject_proposed_or_requested_courses
  after UPDATE
  ON public."Student_registers"
  FOR EACH ROW
  WHEN (((new.register_status = 'approved'::register_status) AND 
  ((old.register_status = 'proposed'::register_status) OR (old.register_status 
   = 'requested'::register_status))))
  EXECUTE PROCEDURE public.reject_proposed_requested_courses();

在下表中:

CREATE TABLE public."Student_registers"
(
  lab_grade real,
  exam_grade integer,
  register_status register_status NOT NULL,
  amka integer NOT NULL,
  serial_number integer NOT NULL,
  final_grade real,
  CONSTRAINT "Student_registers_amka_fkey" FOREIGN KEY (amka)
      REFERENCES public."Student" (amka) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "Student_registers_serial_number_fkey" FOREIGN KEY (serial_number)
      REFERENCES public."CourseRun" (serial_number) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

我的密钥是(amka,serial_number),在更新触发器期间唯一改变的是register_status。(但它尚未被声明为测试问题的主键)。

register_status类型也在这里:

CREATE TYPE public.register_status AS ENUM
   ('proposed',
    'requested',
    'approved',
    'rejected',
    'pass',
    'fail');
ALTER TYPE public.register_status
  OWNER TO postgres;

基本上当有人将申请更改为“已批准”时,我需要检查申请是否可以被批准...否则会被触发器拒绝。 所以,我做了以下触发器功能:

CREATE OR REPLACE FUNCTION public.reject_proposed_requested_courses()
  RETURNS trigger AS
$BODY$
begin
if(((select count(*) from "Student_registers" sr2 where amka=new.amka and
 sr2.register_status='approved')<=10)and  --less than 10
   [...] (more checks that work just fine after many tests)

   )then return new;
 else update "Student_registers" sr1 set register_status='rejected' 
      where (old.amka=sr1.amka and old.serial_number=sr1.serial_number);
   return new;
 end if;
end;
$BODY$
LANGUAGE plpgsql VOLATILE

我的问题是条件“小于10”...每个学生可以有10个最大适用'已批准',所以每次我需要检查是否有10个申请批准在他的amka ...这作为如果我尝试单独更改,但如果我大规模更改所有适用(超过10)批准触发器只是'拒绝'所有这些。我主要担心的是“每一行”并没有真正完成我期望它做的工作。如果同时有15个更改,我想接受前10个“批准”并“拒绝”其中的5个。我该怎么做才能做到这一点?

感谢

0 个答案:

没有答案