创建触发器函数是 psql "syntax error at or near "CREATE""

Creating Trigger function is psql "syntax error at or near "CREATE""

这是我的 postgreSQL 代码

CREATE FUNCTION connectedExhibitionFunction()
RETURNS trigger AS
$$
BEGIN
        IF (SELECT COUNT("exName") FROM Exhibitions WHERE NEW."exName" = "exName") > 0 THEN
                IF (SELECT Count(doorLoc1) FROM Doors, ExhibitionLocations WHERE (dorLoc1=NEW.elLocation AND dorLoc2=elLocations) OR (dorLoc2=NEW.elLocation AND dorLoc1=elLocations) > 0 THEN
                        RAISE EXCEPTION 'You can't have the exhibition there, the same exhibition is in an unconnected room';
                END IF;
        END IF;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER connectedExhibitionTrigger
        BEFORE INSERT
        ON ExhibitionsLocations
        EXECUTE PROCEDURE connectedExhibitionFunction();

这就是我遇到的错误

psql:file.txt:62: ERROR:  syntax error at or near "CREATE"
LINE 8: CREATE FUNCTION connectedExhibitionFunction()
        ^
psql:file.txt:67: ERROR:  current transaction is aborted, commands ignored until end of transaction block

我似乎无法找出错误,有人能在这里发现什么吗?

我猜你错过了 Select ")" 并且不能提出例外条款 "can't" 您可以只使用 END 而不是 END IF。据我所知你的问题是这些。

请试试这个。

 IF (SELECT Count(doorLoc1) FROM Doors, ExhibitionLocations 
  WHERE (dorLoc1=NEW.elLocation AND dorLoc2=elLocations) OR 
  (dorLoc2=NEW.elLocation AND dorLoc1=elLocations)) > 0 THEN
  RAISE EXCEPTION 'You cant have the exhibition there, the same exhibition is in an unconnected room';
 END 

您不应使用 count() 函数来测试数据是否存在,而应使用 PERFORM 命令。您还应该 RETURN NEWRETURN NULL 来自触发器函数,否则您的插入将根据定义失败。通过其他一些改进,您将得到这样的结果:

CREATE FUNCTION connectedExhibitionFunction() RETURNS trigger AS $$
BEGIN
    PERFORM * FROM Exhibitions WHERE "exName" = NEW."exName";
    IF FOUND THEN
        PERFORM * FROM Doors, ExhibitionLocations
        WHERE (dorLoc1 = NEW.elLocation AND dorLoc2 = elLocations)
           OR (dorLoc2 = NEW.elLocation AND dorLoc1 = elLocations);
        IF FOUND THEN
            RAISE EXCEPTION 'You can''t have the exhibition there, the same exhibition is in an unconnected room';
            RETURN NULL; -- Make the INSERT fail
        END IF;
    END IF;
    RETURN NEW; -- Make the INSERT succeed
END;
$$ LANGUAGE plpgsql;