postgresql - 错误 : duplicate key value violates unique text constraint

标签 postgresql postgresql-10

我有一个看起来像这样的表“A”:

 key |   name
-----+-----------------------
 aa  | AName
 bb  | BName
 cc  | CName

另一个看起来像这样的表'B'

P_name | p_key | key
-----+-------+-----
dd   | 1801  | aa
ee   | 1108  | aa

这是完整的功能

 CREATE OR REPLACE FUNCTION add_B( p_name text, p_key varchar(9), key char(2), name text )
 RETURNS boolean AS $$
 DECLARE
    did_insert boolean := false;
    found_count integer;
    the_key text;
    the_name text;
 BEGIN

SELECT a.key INTO the_key
FROM A a
WHERE a.key = the_key
LIMIT 1;

IF the_key IS NULL THEN
        INSERT INTO A (key, name)
        VALUES (key, name)
        RETURNING add_B.key INTO the_key;
        did_insert := true;
 END IF;

RAISE NOTICE 'A is found %', the_key;
    INSERT INTO B (p_name, p_key, key)
    VALUES (p_name, p_key, key);

    RETURN did_insert;
END;
$$ LANGUAGE plpgsql;

问题是每当我运行

SELECT add_key('newname','p_key','aa','AName');

返回

ERROR: duplicate key value violates unique constraint "A_pkey"

我该如何解决这个错误?

最佳答案

the_key 为 null,因此您可能指的是下面 SELECT 的 WHERE 子句中的其他变量:

SELECT a.key INTO the_key
FROM A a
WHERE a.key = the_key
LIMIT 1;

您可能应该改写为:

SELECT A.key INTO the_key
FROM A
WHERE A.key = key -- note the change of variable here
LIMIT 1;

那么,你的 INSERT 语句也应该包括你的表,所以添加它

INSERT INTO A (key, name) ...

您可以像以前那样使用 add_B.name 之类的别名来指定值的来源,或者像这样简单地为此函数使用变量行为设置:

CREATE FUNCTION ...
#variable_conflict use_variable -- add this
DECLARE
...

关于postgresql - 错误 : duplicate key value violates unique text constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449632/

相关文章:

postgresql - 在 PostgreSQL 中使用 COPY FROM 命令插入多个表

postgresql - 如何正确使用 Postgres 中函数的默认模式权限?

postgresql - 如何聚合 JSONB PostgreSQL 10

postgresql - 获取分区表的表大小(Postgres 10+)

java - jOOQ 在 PostgreSQL 中选择不同的数组聚合

postgresql - 如何使用 PostgreSQL 和 TypeORM 进行查询,其中表具有 JSON 类型列

json - 如何检查 Postgres 中是否存在 json 键?

performance - Postgres 在索引构建期间没有使用足够的 CPU!

c++ - 有哪些使用 PostgreSQL 以 C/C++ 编写的开源应用程序?