Search Postgresql Archives

Re: [HACKERS] Update on Insert

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2009/11/16 Robert Haas <robertmhaas@xxxxxxxxx>:
> On Mon, Nov 16, 2009 at 1:31 PM, SebiF <sfeher@xxxxxxxxx> wrote:
>> Hi Everyone,
>>
>> Given a table "Items" with a PK "item1" and "Qty" - a numeric column
>> I'd like to define a way in Postgres to insert when item11 doesn't
>> exist already in "Items" and update the Qty by adding the new quantity
>> to the existent when the item11 exists. What is a good approach and
>> where should I be looking for details. Thanks.
>>
>> Sebastian
>
> This is not a -hackers question; please use pgsql-general instead.
>
> Also see example 38-2 here:
> http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html
>
> ...Robert
>

You could try something like the following:

CREATE FUNCTION update_items(item_value TEXT, qty_value INTEGER)
RETURNS BOOL AS $$
DECLARE item_rec RECORD;
BEGIN
	SELECT INTO item_rec * FROM items WHERE item = item_value;
	
	IF item_rec.item IS NULL THEN
		INSERT INTO items (item, qty) VALUES (item_value, qty_value);
		RAISE NOTICE 'added';
		RETURN true;
	ELSE
		UPDATE items SET qty = qty + qty_value WHERE item = item_value;
		RAISE NOTICE 'updated';
		RETURN true;
	END IF;
END;
$$ LANGUAGE plpgsql

Then use:

SELECT update_items('monkey',9);

You could probably also create an updateable view with a rule applied
or something.

Thom

-- 
Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux