我有一个像这样的表“ 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');
返回
错误:重复的键值违反了唯一约束“ A_pkey”
如何处理此错误?
答案 0 :(得分:2)
BitConverter.Int32BitsToSingle()
为null,因此您可能在WHERE子句中为以下SELECT表示其他变量:
the_key
您可能应该将其改写为:
SELECT a.key INTO the_key
FROM A a
WHERE a.key = the_key
LIMIT 1;
然后,您的INSERT语句也应该包含您的表,因此添加它
SELECT A.key INTO the_key
FROM A
WHERE A.key = key -- note the change of variable here
LIMIT 1;
您可以使用INSERT INTO A (key, name) ...
这样的别名来指定值的来源,也可以像下面这样简单地对该函数使用可变行为设置:
add_B.name