Backpatch merge_db() example for PL/PgSQL to 8.0. Patch from David

Fetter, fixes by Neil Conway.
This commit is contained in:
Neil Conway 2005-10-06 21:21:27 +00:00
parent ce150c4a8b
commit 20f5a328e5

View File

@ -1,5 +1,5 @@
<!--
$PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.57.4.1 2005/01/22 23:05:47 momjian Exp $
$PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.57.4.2 2005/10/06 21:21:27 neilc Exp $
-->
<chapter id="plpgsql">
@ -1998,6 +1998,44 @@ END;
don't use <literal>EXCEPTION</> without need.
</para>
</tip>
<example id="plpgsql-upsert-example">
<title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
<para>
This example uses exception handling to perform either
<command>UPDATE</> or <command>INSERT</>, as appropriate.
<programlisting>
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
</programlisting>
</para>
</example>
</sect2>
</sect1>