从Postgres中的对象数组插入唯一值

时间:2018-08-21 21:15:25

标签: postgresql sql-insert bulkinsert jsonb

我一直试图从对象数组中将一组唯一代码输入到postgres中。到目前为止,这是我所拥有的,但是在INTO附近一直持续失败。我以前尝试过循环版本,但从未结束插入任何内容,但也不会产生任何错误。下面是理想的批量插入方法,不需要任何FOR循环。

CREATE OR REPLACE FUNCTION "InsertCodes" (
  "@codes"                  JSONB,
  "@type"                   TEXT
)
RETURNS void AS
$func$
DECLARE "id"                UUID;
BEGIN
  "id" = uuid_generate_v4();
  SELECT * FROM (
    SELECT *
    FROM jsonb_array_elements("@codes")
  ) AS c (
-- fails below
    INSERT INTO
      "codes" (
        "id",
        "code",
        "name",
        "type"
      )
    VALUES (
      "id",
      c."code",
      c."name",
      "@type"
    );
    ON CONSTRAINT ("code")
    DO NOTHING
    RETURNING 1;
  );
END;
$func$ LANGUAGE PLPGSQL;

@codes如下所示:

[
  {
    "code": 1234,
    "name": "numeric"
  },
  {
    "code": "1k1l2k",
    "name": "alphanumeric"
  }
]

2 个答案:

答案 0 :(得分:2)

查询应如下所示:

"id" = uuid_generate_v4();
INSERT INTO "codes" ("id", "code", "name", "type")
SELECT "id", item->>'code', item->>'name', "@type"
FROM jsonb_array_elements("@codes") AS item
ON CONFLICT ("code") DO NOTHING;

请注意,将为通过jsonb数组传递的所有代码插入相同的"id"。如果它是主键,则应该为每个代码分别生成"id"

INSERT INTO "codes" ("id", "code", "name", "type")
SELECT uuid_generate_v4(), item->>'code', item->>'name', "@type"
FROM jsonb_array_elements("@codes") AS item
ON CONFLICT ("code") DO NOTHING;

答案 1 :(得分:0)

很难理解您要做什么。也许是这样:

CREATE OR REPLACE FUNCTION "InsertCodes" (
  "@codes"                  JSONB,
  "@type"                   TEXT
)
RETURNS void AS
$func$
DECLARE "id"                UUID;
BEGIN
  "id" = uuid_generate_v4();

  with c("code", "name") as
  (
  SELECT codes->>'code', codes->>'name'
  FROM jsonb_array_elements("@codes") t(codes)
  ) 
-- fails below
    INSERT INTO 
      "codes" (
        "id",
        "code",
        "name",
        "type"
      )
    select 
      "id",
      c."code",
      c."name",
      "@type"
    from c
    ON CONFLICT ON CONSTRAINT "code"
    DO NOTHING;
END;
$func$ LANGUAGE PLPGSQL;