插入JSON值并忽略重复的键/冲突

时间:2018-07-27 13:52:55

标签: sql json postgresql

下面的我的SP处理接收JSON中的标识符列表,解压值并将其插入表中。但是,我想确保这些值是唯一的。我有一个名为“ UniqueListing”的唯一索引集,在它们上设置了列IdentifierURL

我想确保仅插入唯一的ID,而对已经存在的值不做任何事情。我还想确保不会将它们作为响应的一部分返回。

CREATE OR REPLACE FUNCTION "RecordProcessingList" (
  "@Identifiers" JSON,
  "@Source"      VARCHAR(25)
)
RETURNS TABLE (
  "ID"         UUID,
  "Identifier" VARCHAR(50)
) AS
$func$
BEGIN
  RETURN QUERY
  INSERT INTO
    "Listings" AS l (
      "ID",
      "Identifier",
      "Source",
      "URL",
      "Checksum",
      "Status"
    )
  (
    SELECT
      UUID_GENERATE_V4(),
      key::TEXT,
      "@Source",
      TRIM(BOTH '"' FROM value::TEXT)::TEXT AS value,
      '',
      'PROCESSING'
    FROM
      JSON_EACH("@Identifiers")
  )
  ON CONFLICT (
    "Identifier"
  )
  DO NOTHING
  RETURNING
    l."ID",
    l."Identifier";
END;
$func$ LANGUAGE PLPGSQL;

1 个答案:

答案 0 :(得分:0)

似乎您需要添加

ON CONFLICT (
  "Identifier","URL"
)
DO NOTHING