错误:列“semester_id”的类型为整数,但表达式的类型为boolean

时间:2018-04-29 12:54:22

标签: postgresql sql-insert plpgsql auto-increment database-trigger

我在PostgreSQL中创建了这个PL / pgSQL触发器函数:

CREATE or replace FUNCTION public.trigger31()
        RETURNS trigger
        LANGUAGE 'plpgsql'
        COST 100
        VOLATILE NOT LEAKPROOF 
    AS $BODY$
    begin
        if(TG_OP='INSERT') then
            if(New.start_date>(select max(end_date) from "Semester") and New.end_date>New.start_date) then

                Insert Into "Semester" (semester_id,academic_year,academic_season,start_date,end_date,semester_status)
                values (New.semester_id=(select max(s.semester_id)+1 from "Semester" s):: integer,
                        new.academic_year= academic_year_trig(),
                        new.academic_season=academic_season_trig(),
                        new.start_date,new.end_date,
                        new.semester_status=semester_stat_trig()
                    );
                return NEW;
            else
                RAISE EXCEPTION 'Invalid start_date or end_date';
            end if;
        end if;
    end;
$BODY$;

尝试执行它,我收到此错误:

ERROR:  column "semester_id" is of type integer but expression is of type boolean
LINE 2:    values (New.semester_id=(select max(s.semester_id)+1 from...

我不确定为什么。我cast表达了New.semester_id 同样的错误。也尝试了这个:

New.semester_id=(select max(s.semester_id):: integer +1 from "Semester" s)

我仍然有同样的错误。

1 个答案:

答案 0 :(得分:2)

好像你错误地混合了INSERTUPDATE语法。它可能会像这样工作:

...
            INSERT INTO "Semester" (semester_id, academic_year, academic_season, start_date, end_date, semester_status)
            VALUES ((select max(s.semester_id) + 1 from "Semester" s),
                    academic_year_trig(),
                    academic_season_trig(),
                    new.start_date,
                    new.end_date,
                    semester_stat_trig()
                   );
...

但后来我怀疑你也误解了触发器是如何工作的。如果该触发函数用于表ON INSERT上的触发器"Semester",它将触发无限循环 - 除了通常是无意义之外。阅读关于triggerstrigger functions的精细手册。

除此之外,您似乎需要首先阅读serialIDENTITY列: