Postgresql 在函数中UPSERT语法,该函数对表中两列的组合具有唯一约束
我试图在一个表上的函数中使用UPSERT语法,该表在两列的组合上包含唯一约束,但我收到一个错误,它说“没有与冲突规范匹配的唯一或排除约束” 奇怪的是,同一个查询在函数外部工作得很好 那么,假设我有一个下表:Postgresql 在函数中UPSERT语法,该函数对表中两列的组合具有唯一约束,postgresql,postgresql-9.5,Postgresql,Postgresql 9.5,我试图在一个表上的函数中使用UPSERT语法,该表在两列的组合上包含唯一约束,但我收到一个错误,它说“没有与冲突规范匹配的唯一或排除约束” 奇怪的是,同一个查询在函数外部工作得很好 那么,假设我有一个下表: CREATE TABLE IF NOT EXISTS test ( id SERIAL, col1 VARCHAR NOT NULL, col2 VARCHAR NOT NULL, UNIQUE(col1, col2) ); 现在我可以做这样的插入(效果很好): 现在我想在
CREATE TABLE IF NOT EXISTS test (
id SERIAL,
col1 VARCHAR NOT NULL,
col2 VARCHAR NOT NULL,
UNIQUE(col1, col2)
);
现在我可以做这样的插入(效果很好):
现在我想在函数中使用这个查询:
CREATE OR REPLACE FUNCTION test_func(col1 VARCHAR, col2 VARCHAR)
RETURNS INTEGER AS $$
#variable_conflict use_variable
DECLARE
rowid INTEGER;
BEGIN
INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id INTO rowid;
RETURN rowid;
END;
$$ LANGUAGE PLPGSQL;
但是当我调用函数时,我得到了一个错误:
SELECT test_func('val1', 'val2');
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
CONTEXT: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement
********** Error **********
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
SQL state: 42P10
Context: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement
有什么问题吗?将您的参数重命名为例如
p\u col1、p\u col2
@a\u horse\u with\u no\u name谢谢,您是对的!我发现错误消息有误导性。请将您的参数重命名为例如p\u col1,p\u col2
@a\u horse\u with\u no\u name谢谢,您是对的!我发现错误消息有误导性。
SELECT test_func('val1', 'val2');
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
CONTEXT: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement
********** Error **********
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
SQL state: 42P10
Context: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement