如何在返回子句中将表声明为现有表的%TYPE?

时间:2019-04-04 09:29:23

标签: postgresql

这是功能声明的一部分,该功能可将费用从一个帐户转移到另一个帐户,并收取一定费用。它必须返回借方的完整记录。现在,它被声明为返回表和所有行,就像这样:

  CREATE OR REPLACE FUNCTION SPACE(
      debit RECORD,
      credit RECORD,
      howmuch INTEGER,
      fee INTEGER )
  RETURNS TABLE(
    id BIGINT,
    client_id BIGINT,
    tag VARCHAR(128),
    amount INTEGER,
    currency VARCHAR(12),
    status purse_status,
    created_at timestamp without time zone,
    updated_at timestamp without time zone ) AS $BODY$
  BEGIN -- etc

但是,我确实有4个重载函数,并且我不想在更改表“ purses”后更改所有这些声明。下面的示例不起作用,只是语法错误。所以问题是:我可以在短时间内用purses%TYPE之类的语法声明return语句吗?

   CREATE OR REPLACE FUNCTION SPACE(
      debit RECORD,
      credit RECORD,
      howmuch INTEGER,
      fee INTEGER )
    RETURNS purses%TYPE AS $BODY$
    BEGIN
      UPDATE purses
        SET amount = amount - howmuch - fee
        WHERE id = debit.id;

      UPDATE purses
        SET amount = amount + howmuch
        WHERE purses.id = credit.id;

      UPDATE purses
        SET amount = amount + fee
        WHERE client_id = 0 AND currency = credit.currency AND tag = 'space';

      RETURN QUERY SELECT * FROM purses WHERE purses.id = debit.id;
      RETURN;
    END $BODY$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:1)

您可以返回一组表类型:

CREATE OR REPLACE FUNCTION SPACE(
      debit RECORD,
      credit RECORD,
      howmuch INTEGER,
      fee INTEGER )
  RETURNS setof purses
....