ERROR: duplicate key value violates unique text constraint

ERROR: duplicate key value violates unique text constraint

我有一个 table 'A' 看起来像这样:

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

另一个 table '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');

它returns

ERROR: duplicate key value violates unique constraint "A_pkey"

我该如何解决这个错误?

the_key 为空,因此您可能指的是下面 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 语句还应包括您的 table,因此添加它

INSERT INTO A (key, name) ...

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

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