PostgreSQL返回一个自定义数据类型的函数 [英] PostgreSQL return a function with a Custom Data Type

查看:882
本文介绍了PostgreSQL返回一个自定义数据类型的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数来返回我创建的类型,但是当我执行它时,它说类型不存在。我想这是因为它不知道自定义类型。

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 custom type.

UDT:

CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG');

功能:

 CREATE FUNCTION roomCode(id int ) RETURNS building_code AS 
$$
 SELECT building_code FROM venue as v WHERE id = v.id;
$$ LANGUAGE SQL;


推荐答案

这应该是正常的。 enum 应该不成问题。测试Postgres 9.1和9.2

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);

...


  • 9.2之前版本中,您只能使用 位置(数字)参数 $ 1 在SQL函数中(不像plpgsql函数)。
    9.2 + 中,列名优先,所以 WHERE 子句将始终为TRUE,并且所有行都有资格 - 除了您的函数仅返回第一个,因为它不会返回 SETOF building_code

    重新命名参数或使用位置参数,或者最好是两者。

    如果您必须使用冲突的参数名称,则可以使用函数名称来覆盖首选项以限定参数。喜欢:

  • 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


  • 您不应该使用类型名称作为列名。 不加引号的混合大小写名称,例如 roomCode ,它将折叠为小写,除非您双引号:roomCode


  • You shouldn't use the type name as column name.

    - > SQLfiddle 与3个变体

    ->SQLfiddle with 3 variants

    这篇关于PostgreSQL返回一个自定义数据类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆