在postgresql中插入或更新9.1
我有一堆插入语句,其列表的列数各不相同,如果记录不存在,我需要执行这些查询。我试图将其作为在postgresql中插入或更新9.1
do $$
begin
IF not exists (SELECT 1 FROM gst_type_customer WHERE name = 'Unregistered') THEN
insert into gst_type_customer(create_date,write_date,create_uid,write_uid,name) values((now() at time zone 'UTC'),(now() at time zone 'UTC'),1,1,'Unregistered');
END IF;
end
$$
即使上面的代码不工作,虽然实现了批量查询,将需要大量的时间,所以我想制作一个存储过程,我可以打电话为
merge_check(insertquery,name[column to check for duplication],value)
的,但我无法直接执行插入查询。
到目前为止,我还拿出
CREATE OR REPLACE FUNCTION merge_tabla(data text)
RETURNS void AS
$BODY$
BEGIN
execute(data);
END;
$BODY$
LANGUAGE plpgsql
select merge_table("insert into gst_type_customer(name) values('Unregistered')")
,但我得到一个错误说
列 “插入gst_type_customer(名称)VALUES( '未注册')” 不存在
错误你得到被调用函数时使用双引号引起的。这应该工作:
select merge_table(E'insert into gst_type_customer(name) values(\'Unregistered\')'::text)
您需要在原来的查询字符串使用单引号(双引号用于列名,单引号字符串文字)和逃避任何单引号。
谢谢你解决了这个问题 –
您可以使用这样的INSERT ... SELECT
:
INSERT INTO gst_type_customer(create_date, write_date, create_uid, write_uid, name)
SELECT (now() at time zone 'UTC'), (now() at time zone 'UTC'), 1, 1, 'Unregistered'
WHERE NOT EXISTS (
SELECT *
FROM gst_type_customer
WHERE name = 'Unregistered'
)
虽然可以为单个查询工作,但我无法为每个查询实现相同的功能,但是可以在存储过程中实现它们吗? –
的Postgres 9.1支持合并命令 https://www.postgresql.org/message-id/attachment/23520/sql-merge.html
样本:
MERGE CustomerAccount CA
USING (SELECT CustomerId, Sum(TransactionValue) As TransactionSum
FROM Transactions
WHERE TransactionId > 35345678
GROUP BY CustomerId) AS T
ON T.CustomerId = CA.CustomerId
WHEN MATCHED
UPDATE SET Balance = Balance - TransactionSum
WHEN NOT MATCHED
INSERT (CustomerId, Balance)
VALUES (T.CustomerId, T.TransactionSum)
;
INSERT INTO xxx SELECT ...要插入的值... WHERE NOT EXISTS(SELECT * FROM xxx WHERE ... exists condition ...)'? –
感谢您的回复, –
感谢您的回复,是不是像上面的代码检查,如果它不存在,那么它插入,该代码段工作正常,可以给我一个例子,如果我我不理解。 –