PostgreSQL return a function with a Custom Data Type

情到浓时终转凉″ 提交于 2019-11-29 18:03:11

This should just work. The enum should not be a problem. Tested with Postgres 9.1 and 9.2

CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG');
CREATE TEMP TABLE venue (id int PRIMARY KEY, building_code building_code);
INSERT INTO venue VALUES (1, 'ENG');

CREATE OR REPLACE FUNCTION room_code(_id int) --!
  RETURNS building_code AS 
$func$
SELECT building_code FROM venue v WHERE v.id = $1 -- !
$func$ LANGUAGE SQL;

SELECT * FROM room_code(1);

Except ...

  • In versions before 9.2 you can only use positional (numeric) parameters ($1) in SQL functions (unlike plpgsql functions).
    In 9.2+ the column name would take precedence, so that the WHERE clause of your original code would always be TRUE and all rows would qualify - except that your function only returns the first, since it does not return a SETOF building_code.
    Either rename your parameter or use positional parameter or, preferably, both.
    If you must use conflicting parameter names, you can override the preference by using the function name to qualify the parameter. Like:

    ... WHERE v.id = room_code.id
    
  • You shouldn't use the type name as column name.

  • You should not use unquoted mixed case names like roomCode, which will be folded to lower case, unless you double-quote: "roomCode".

->SQLfiddle with 3 variants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!