在postgresql 9.1中插入或更新

时间:2017-06-15 07:28:33

标签: postgresql duplicates

我有一堆插入语句,它们各自的表有不同数量的列,如果记录不存在,我需要执行这些查询。我试图将其实现为

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(name)值(' Unregistered')"不存在

3 个答案:

答案 0 :(得分:1)

您可以像这样使用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'
)

答案 1 :(得分:1)

postgres 9.1支持merge命令 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)
;

答案 2 :(得分:1)

The error You are getting is caused by using double quotes when calling the function. This should work:

select merge_table(E'insert into gst_type_customer(name) values(\'Unregistered\')'::text)

You need to use single quotes (double quotes are used for column names, single quotes for string literals) and escape any single quotes in the original query string.