postgresql Postgres将数据插入复合类型[重复]

7y4bm7vi  于 11个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(137)

此问题在此处已有答案

Correct syntax for array of composite type(2个答案)
4天前关闭。
我在Postgres工作。我有下面的复合类型

CREATE TYPE negotiation.diff_type AS 
(
    operation int,
    content text
);

字符串
这是我的table

CREATE temp TABLE temp_input 
(
    indication_request_id int, 
    para_id int, 
    line_number int, 
    document_id int, 
    modified_content text, 
    created_by text, 
    diffs diff_type[]
);


在表中,我使用的是diff复合类型。
下面我将数据插入表中。

INSERT INTO temp_input (myid, para_id, line_number, document_id,modified_content,created_by, diffs)
VALUES (20,2893,10,18,'my content','user1', '{(1,"DDD")"}');


我得到这个错误:
错误:格式错误的数组文字:“{(1,“DDD”)"}”

toe95027

toe950271#

你需要用引号将数组的每个元素括起来,然后在复杂类型的字面量中转义引号:

INSERT INTO temp_input
(indication_request_id, para_id, line_number, document_id,modified_content,created_by, diffs)
VALUES (20,2893,10,18,'my content','user1', '{"(1,\"DDD\")"}');

字符串

SQLFiddle Demo

xurqigkl

xurqigkl2#

下面是如何创建一个包含negotiation.diff_type数组的文字:

array['(1,abc)','(2,def)']::negotiation.diff_type[]

字符串

qhhrdooz

qhhrdooz3#

概念验证

演示命令的正确语法是:

INSERT INTO temp_input (indication_request_id, para_id, line_number, document_id,modified_content,created_by, diffs)
VALUES (20,2893,10,18,'my content','user1', '{"(1,DDD)"}');

字符串
多个输入行和多个数组元素的正确语法:

INSERT INTO temp_input (indication_request_id, para_id, line_number, document_id,modified_content,created_by, diffs)
VALUES
  (2,3,10,18,'my content','user1', '{"(1,DDD)","(2,foo)"}')
, (3,4,10,18,'my content','user1', '{"(1,DDD)","(2,foo)","(3,\"Weird \\\\string\"\"\")"}')
;


只需向Postgres询问正确的语法(psql摘录):

test=> BEGIN;
BEGIN
test=*> CREATE TYPE diff_type AS (
test(*>     operation int,
test(*>     content text
test(*> );
CREATE TYPE
test=*> CREATE TEMP TABLE syntax_demo OF diff_type;
CREATE TABLE
test=*> INSERT INTO syntax_demo VALUES
test-*>   (1, 'DDD')
test-*> , (2, 'foo')
test-*> , (3, 'Weird \string"');
INSERT 0 3
test=*> 
test=*> SELECT ARRAY(SELECT t FROM syntax_demo t) AS proper_syntax;
                    proper_syntax                     
------------------------------------------------------
 {"(1,DDD)","(2,foo)","(3,\"Weird \\\\string\"\"\")"}   -- !!!
(1 row)

test=*> ROLLBACK;


试验项目:

SELECT '{"(1,DDD)","(2,foo)","(3,\"Weird \\\\string\"\"\")"}'::diff_type[];


反向测试:

SELECT (('{"(1,DDD)","(2,foo)","(3,\"Weird \\\\string\"\"\")"}'::diff_type[])[3]).content;


fiddle
(Note dbfiddle.uk中的当前错误显示:它吞下\的内部级别。
正如你所看到的,你需要在每一行文字(=复合元素类型)周围加上双引号,但在嵌套的字符串周围不要加双引号,除非它包含特殊字符。然后你必须转义这些,这在此时会因为多层嵌套而变得非常混乱。让Postgres为你做吧。
参见:

  • 复合类型数组的正确语法
  • 不使用ARRAY[]的嵌套复合类型的数组

更好

不要从开始就去那里。就像Laurenz评论的那样,表定义中的复合数据类型通常表明对正确的数据库设计的误解。考虑一个中间规范化的模式。

相关问题