SQL( "if ...exists...),how to do it in the PostgreSQL?

Started by Ericover 24 years ago4 messages
#1Eric
e-lz@263.net

��
I can realize this function in the SYBase,but How can i do it in the PostgreSQL?

/****SQL***/
if not exists(select id from test) insert into test(id) values (280);
/*********/

_____________________________________________
�����Ʒ�����У��� http://shopping.263.net/category21.htm
��ƷС�ҵ�ӭ������ http://shopping.263.net/category23.htm

#2Peter Eisentraut
peter_e@gmx.net
In reply to: Eric (#1)
Re: SQL( "if ...exists...),how to do it in the PostgreSQL?

Eric writes:

I can realize this function in the SYBase,but How can i do it in the PostgreSQL?

/****SQL***/
if not exists(select id from test) insert into test(id) values (280);
/*********/

Write a function in PL/pgSQL.

--
Peter Eisentraut peter_e@gmx.net http://funkturm.homeip.net/~peter

#3Tom Lane
tgl@sss.pgh.pa.us
In reply to: Peter Eisentraut (#2)
Re: SQL( "if ...exists...),how to do it in the PostgreSQL?

if not exists(select id from test) insert into test(id) values (280);

Write a function in PL/pgSQL.

That particular case could be handled like so:

insert into test(id) select 280 where not exists(select id from test);

The select produces either zero or one row depending on whether its
WHERE is true. Voila, problem solved. It's even nearly standard ;-)
although in something like Oracle you'd have to add "from dual", I
think.

regards, tom lane

#4Robert Forsman
thoth@purplefrog.com
In reply to: Tom Lane (#3)
Re: SQL( "if ...exists...),how to do it in the PostgreSQL?

Eric writes:

I can realize this function in the SYBase,but How can i do it in the PostgreSQL?

/****SQL***/
if not exists(select id from test) insert into test(id) values (280);
/*********/

I don't know if this is SQL92, but

insert into test(id) select 280 where not exists(select id from test);