PostgreSQL函数检查数组中的枚举值

时间:2013-08-14 21:10:37

标签: sql arrays postgresql enums postgresql-9.2

类型:

CREATE TYPE equipment AS ENUM ('projector','PAsystem','safe','PC','phone');
CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG');

表:

CREATE TABLE venue (
   id INTEGER DEFAULT NEXTVAL('venue_id_seq')
 , building_code building_code
 , floorNo int
 , roomNo int
 , width int
 , length int
 );

CREATE TABLE lecture_room (
   id INTEGER DEFAULT NEXTVAL('lecture_id_seq')
 , seatCount int
 , equipment equipment[]
) INHERITS(venue);

功能:

CREATE or REPLACE FUNCTION hasProjector(_id int ) RETURNS boolean AS 
$$
code to check if there exists a projector in the equipment array of lecture_room
$$ LANGUAGE SQL;

我不能100%确定要放入函数的SQL代码以及如何获取布尔值作为结果。

1 个答案:

答案 0 :(得分:1)

使用ANY检查数组是否包含某个元素:

SELECT TRUE
FROM   lecture_room
WHERE  id = _id
AND    'projector' = ANY (equipment)

返回TRUE或NULL。如果您需要TRUE / FALSE,请使用EXISTS

SELECT EXISTS (
   SELECT 1
   FROM   lecture_room
   WHERE  id = _id
   AND    'projector' = ANY (equipment)
   )
顺便说一下,在这种情况下,你不需要一个显式的强制转换('projector'::equipment),但它也不会受到伤害。