Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert or update in postgresql 9.1

I have a bunch of insert statements with varying number of columns for their respective tables, i need to execute these queries if the record doesn't already exist.I have tried to implement this as

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
$$

even though the above code does work although implementing for a bulk of queries would require a lot of time, so i thought of making a stored procedure which i could call as

merge_check(insertquery,name[column to check for duplication],value)

but I'm unable to execute the insert query directly.

so far I have come up with

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')")

but I get an error saying

column "insert into gst_type_customer(name) values('Unregistered')" does not exist

like image 567
Omi Harjani Avatar asked Feb 17 '26 01:02

Omi Harjani


1 Answers

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.

like image 180
Roman Hocke Avatar answered Feb 18 '26 15:02

Roman Hocke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!