PL / PgSQL函数返回空行而不是带有ids的行

时间:2013-09-26 17:39:27

标签: postgresql plpgsql postgresql-8.4

我打算通过临时表中的策略更改来记录用户ID。以下应返回记录的ID,但它确实返回空行。不知何故,ids丢失了:S行数没问题,ids在桌子上,我不知道我做错了什么......

BEGIN;
SELECT * FROM policy_change_update(ARRAY[1,2,3]);
SELECT * FROM user_read_all_by_policy_change();
COMMIT;

功能:

policy_change_provide_store:

CREATE FUNCTION policy_change_provide_store ()
  RETURNS VOID
AS
  $BODY$
  BEGIN
    CREATE TEMPORARY TABLE policy_change (
      user_id INT4
    );
    EXCEPTION WHEN duplicate_table THEN
    RETURN;
  END;
  $BODY$
LANGUAGE plpgsql VOLATILE;

policy_change_update

CREATE FUNCTION policy_change_update (
  IN user_ids INT4 []
)
  RETURNS VOID
AS
  $BODY$
  BEGIN
    PERFORM policy_change_provide_store();
    INSERT INTO policy_change
    SELECT inserted_user_id FROM unnest(user_ids) AS inserted_user_id
    WHERE NOT EXISTS(SELECT 1 FROM policy_change WHERE user_id = inserted_user_id);
  END;
  $BODY$
LANGUAGE plpgsql VOLATILE;

user_read_all_by_policy_change

CREATE FUNCTION user_read_all_by_policy_change ()
  RETURNS TABLE (
  user_id INT4
  )
AS
  $BODY$
  BEGIN
    PERFORM policy_change_provide_store();
    RETURN QUERY
    SELECT user_id FROM policy_change ORDER BY user_id DESC;
    IF NOT FOUND THEN
      RAISE SQLSTATE 'UE404' USING MESSAGE = 'not found';
    END IF;
  END;
  $BODY$
LANGUAGE plpgsql VOLATILE;

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

解决方案:

SELECT policy_change.user_id FROM policy_change ORDER BY policy_change.user_id DESC;

而不是

SELECT user_id FROM policy_change ORDER BY user_id DESC;