Informix到PostgreSQL - 事务功能

时间:2015-05-24 09:10:41

标签: sql postgresql transactions plpgsql informix

我需要将我的Informix函数转换为PostgreSQL。问题是我知道PostgreSQL不允许在函数中调用BEGIN WORK和COMMIT,所以我不知道如何处理异常并以这种方式回滚。

我要转换的功能如下所示:

CREATE PROCEDURE buyTicket(pFlightId LIKE transaction.flightId, pAmount LIKE transaction.amount) 
      DEFINE sqle, isame INTEGER; 
      DEFINE errdata CHAR(80); 
      ON EXCEPTION SET sqle, isame, errdata 
         ROLLBACK WORK; 
         IF sqle = -530 AND errdata LIKE '%chkfreespots%' THEN 
            RAISE EXCEPTION -746, 0, 'Not enough free spots';               
         ELSE 
            RAISE EXCEPTION sqle, isame, errdata; 
         END IF 
      END EXCEPTION; 
   BEGIN WORK; 
   INSERT INTO transaction VALUES (0, pFlightId, pAmount); 
   UPDATE tickets SET freeSpots= freeSpots - pAmount
      WHERE flightId = pFlightId; 
   COMMIT WORK; 
END PROCEDURE; 

1 个答案:

答案 0 :(得分:1)

阅读完评论后,我终于设法解决了这个问题。这是PostgreSQL代码,与我上面发布的Informix相同:

CREATE OR REPLACE FUNCTION buyTicket(pFlightId INT, pAmount INT)
RETURNS VOID AS $$
BEGIN
  INSERT INTO transaction(flightId,amount) VALUES (pFlightId, pAmount); 
  UPDATE tickets SET freeSpots = freeSpots - pAmount
  WHERE flightId = pFlightId; 
EXCEPTION
  WHEN others THEN
    IF sqlerrm LIKE '%chkfreespots%' THEN
       RAISE EXCEPTION  'Not enough free spots';
    ELSE
      RAISE;
    END IF;
END;
$$ LANGUAGE plpgsql;