Inserting a needed record before a select

From: "Jay O'Connor" <joconnor(at)cybermesa(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Inserting a needed record before a select
Date: 2003-04-14 17:36:39
Message-ID: 3.0.1.32.20030414113639.00843100@cybermesa.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

All,

Hello, I'm new to this list but I'm looking for some information.

What I need to do is to find a way to automallically insert a record if it
doesn'
t exist, prior to a SELECT.

Basically, I'm tracking some information based on date and the client
application when retrieving the information knows will that 'current' is
the record with today's date.

What I'd like is a way of of specifiying that when the SELECT is done,
there will be a check that a record exists for the current date and that if
it doesn't exist, a record will be inserted into the table for the current
date and then the SELECT will return the recors including the newly
inserted one.

What I've tried so far is a function that checks for the record, inserts it
if needed, and then returns a cursor that the client can use, but I was
wondering if there was something more direct. I thought of a RULE but I
don't see that they can do processing that expressive.

Here's an example: mytable contains the date based stats information with
another id. All the stats columns are defaulted so just inserting a new
record with the right id and date is sufficient.
=============

CREATE FUNCTION getdatestats (varchar) RETURNS refcursor AS '
DECLARE
myid ALIAS FOR $1;
today date;
ref refcursor;
dummyrow RECORD;

BEGIN

ref := 'statscursor';
SELECT INTO dummyrow * FROM mytable where id = AND statdate = today;
IF NOT FOUND
INSERT INTO mytable (id, statdate) VALUES (myid, today)
END IF;

OPEN ref for SELECT * FROM mytable WHERE id=myid;

RETURN ref;
END;
' LANGUAGE PLPGSQL

=============

Any other ideas? This works but I was wondering if it was possible to do
it without the client needing to do the transaction/cursor handling
(considering I'm only holding up to 30 days worth of data)

Thanks

Jay O'Connor

Responses

Browse pgsql-general by date

  From Date Subject
Next Message scott.marlowe 2003-04-14 17:57:35 Re: Inserting a needed record before a select
Previous Message Tom Lane 2003-04-14 17:00:55 Re: [GENERAL] Problem about pgsql's column alias