【发布时间】:2020-11-08 21:05:17
【问题描述】:
我正在PostgreSQL 中创建一个存储过程,它将首先根据'ID' 检查给定表中是否存在数据。如果是,则将其移动到其他表并在给定表名中插入最新记录。我编写了一个存储过程,我在其中使用硬编码值进行了尝试,它可以按我的需要工作,但是当我试图使其具有通用性时,即创建变量然后在查询中传递这些变量时,它会引发错误。我在下面提到了SO links 和official documentation link,并且能够修改我的存储过程:
下面是我的存储过程:
CREATE OR REPLACE PROCEDURE compareDups(ab integer, b json, tablename varchar)
AS $$
DECLARE
actualTableName varchar := 'testing.'||tablename;
histTableName varchar:= actualTableName ||'_hist';
job_id Integer:=0;
BEGIN --<<<< HERE
EXECUTE 'SELECT id FROM '||actualTableName||' WHERE id =$1' INTO job_id USING ab;
-- if there is data for id in the table then perform below operations
IF job_id IS NOT NULL THEN
EXECUTE FORMAT('INSERT INTO %I as select * from %L where id = $1',histTableName,actualTableName) USING ab;
EXECUTE FORMAT('DELETE FROM %I where id = $1',actualTableName) USING ab;
EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
-- if id is not present then create a new record in the actualTable
ELSE
EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
END IF;
END; --<<<< END HERE
$$
LANGUAGE plpgsql;
所以,虽然creating variables 我只使用了EXECUTE 选项,而calling queries 我使用了EXECUTE FORMAT(...) 选项。
当我尝试调用它时,出现以下错误:
ERROR: syntax error at or near "select"
LINE 1: INSERT INTO "testing.sampletesting_hist" as select * from 't...
^
QUERY: INSERT INTO "testing.sampletesting_hist" as select * from 'testing.sampletesting' where id = $1
CONTEXT: PL/pgSQL function comparedups(integer,json,character varying) line 10 at EXECUTE
SQL state: 42601
我在这里错过了什么?
【问题讨论】:
-
您缺少的是“testing.sampletesting_hist”应该是“testing”。“sampletesting_hist” 而且这个“testing.sampletesting”是无效的。标识符需要双引号。
-
是的,我明白了:)
标签: postgresql stored-procedures