Re: get the oid

From: Josh Berkus <josh(at)agliodbs(dot)com>
To: Niclas Hedell <nick(at)ergodos(dot)com>, pgsql novice <pgsql-novice(at)postgresql(dot)org>
Subject: Re: get the oid
Date: 2003-03-10 15:07:37
Message-ID: 200303100707.37805.josh@agliodbs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Nick,

> I'm not only a novice to pgsql but also to sql in general (as well as
> new in this list)...

Jumping in with both feet, are you?

> Here's my question: Why doesn't the following function work?
>
> create function getoid(name) returns integer as '
> declare
> ret integer;
> tablename alias for $1;
> begin
> select into ret oid from tablename;
> return ret;
> end;'
> language 'plpgsql';

For two reasons:

1) The above query, if you fixed it, would return the OID for the first record
of the table, not the OID for the table. If you want the OID for the table,
query the pg_class system table.

2) If you want to pass a dynamic query string in PL/pgSQL, you need to use a
RECORD loop and pass the query as a string. PL/pgSQL does *not* permit
passing variables as table, column, or other object names ... variables can
only substitute for constants. Thus to get the above to work:

create function getoid(name) returns integer as '
declare
ret integer;
tablename alias for $1;
query_string TEXT;
rec_table RECORD;
begin
query_string := 'SELECT oid FROM ' || tablename;
FOR rec_table IN query_string LOOP
ret := rec_table.oid;
END LOOP;
RETURN ret;
end;'
language 'plpgsql' WITH (ISSTRICT);
(above is 7.2.x syntax).

... though, as I said, this will just get you the OID of the first row of the
table, not the OID of the table itself. Why doyou want the OID, anyway?

Oh, and ISSTRICT is so that the function will return a NULL automatically
whenever NULL Is passed as the tablename.

--
Josh Berkus
josh(at)agliodbs(dot)com
Aglio Database Solutions
San Francisco

In response to

  • get the oid at 2003-03-10 16:49:41 from Niclas Hedell

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Delao, Darryl W 2003-03-10 15:22:25 General Performance questions
Previous Message bryan 2003-03-10 14:57:17 Value of sequence last inserted