PostgreSQL INSERT into an array of enums

谁说胖子不能爱 提交于 2020-05-10 07:35:25

问题


How can I insert an array of enums?
Here is my enum:

CREATE TYPE equipment AS ENUM ('projector','PAsystem','safe','PC','phone');

Then my table has an array of equipment:

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

Here is my ATTEMPT to INSERT:

INSERT INTO lecture_room (building_code, floorNo,  roomNo, length, width
                        , seatCount, equipment) 
VALUES 
('IT', 4, 2, 10, 15 ,120, ARRAY['projector','PAsystem','safe']),

But it gives me the following error:

ERROR: column "equipment" is of type equipment[] but expression is of type text[]
SQL state: 42804
Hint: You will need to rewrite or cast the expression.

回答1:


PostgreSQL doesn't know how to automatically cast input of type text to input of type equipment. You have to explicitly declare your strings as being of type equipment:

ARRAY['projector','PAsystem','safe']::equipment[]

I confirmed this with SQL Fiddle.




回答2:


The alternative to an ARRAY constructor like @Mark correctly supplied is to cast a string literal directly:

'{projector,PAsystem,safe}'::equipment[]

This variant is shorter and some clients have problems with the ARRAY constructor, which is a function-like element.




回答3:


Old question, but a new answer. In modern versions of Postgres (tested with 9.6) none of this is required. It works as expected:

INSERT INTO lecture_room (equipment) VALUES ('{"projector", "safe"}');



回答4:


Additionally to @harm answer, you can skip quotations marks:

INSERT INTO lecture_room (equipment) VALUES ('{projector, safe}');


来源:https://stackoverflow.com/questions/18234946/postgresql-insert-into-an-array-of-enums

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