代码之家  ›  专栏  ›  技术社区  ›  fatyuan

postgresql错误:“RETURNS”处或附近出现语法错误

  •  2
  • fatyuan  · 技术社区  · 8 年前

    我对psql完全陌生。当我使用 http://sqlfiddle.com/ 为了做一些作业,系统会返回这个错误。

    ERROR: syntax error at or near "RETURNS"
    

    感谢您的帮助。 这是我的psql:

    CREATE TABLE HotelStays
    (roomNum INTEGER NOT NULL,
    arrDate DATE NOT NULL,
    depDate DATE NOT NULL,
    guestName CHAR(30) NOT NULL,
    PRIMARY KEY (roomNum, arrDate))
    ;
    
    CREATE OR REPLACE FUNCTION stopInsert RETURNS trigger AS
    $body$
    DECLARE
      availableArrDate DATE;
      checkRoomNum INTEGER;
    BEGIN
      if (NEW.arrDate >= NEW.depDate) then
        return null;
       end if;
    
      checkRoomNum = NEW.roomNum;
    
      select h.depDate into availableArrDate
      from HotelStays h
      where h.roomNum = checkRoomNum
      order by h.depDate DESC
      LIMIT 1;
      if (availableArrDate > NEW.arrDate)
        return null;
      end if;
    END;
    $body$ LANGUAGE plpgsql;
    
    create trigger stopInsert before insert ON HotelStays 
    For each row
    execute procedure stopInsert();
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   a_horse_with_no_name    8 年前

    函数名需要具有 () 其中:

    CREATE OR REPLACE FUNCTION stopInsert() RETURNS trigger AS
                                          ^
    --------------------------------------|
    

    这个 IF 语句也不正确,您缺少 THEN

    if (availableArrDate > NEW.arrDate) then --<< THEN is required
      return null;
    end if;
    

    在SQLFiddle中,您还需要使用不同的语句终止符才能使用嵌入式 ; 在PL/pgSQL代码中:

    enter image description here

    那么你 保持 这个 ; 在函数内部,但替换所有“final” ; 使用 / 在一条线上。这仅在SQLFiddle中是必需的,而在使用命令行客户端时不是必需的 psql 或其他Postgres兼容的SQL客户端。