PostgreSQL return a function with a Custom Data Type

后端 未结 1 579
感动是毒
感动是毒 2020-12-22 11:31

I want to create a function that returns a type that I made, but when I execute it, it says that the type doesn\'t exists. I assume that\'s cause it doesn\'t know about the

相关标签:
1条回答
  • 2020-12-22 11:39

    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

    0 讨论(0)
提交回复
热议问题