开发者

PL/PgSQL: RETURNS TABLE output is comma delimited without values

The following PL/pgSQl script returns the correct number of rows, but the output is a list of开发者_如何学C comma separated values in brackets as follows:

(,,) (,,) (,,) (,,) (,,) . . (,,)

CREATE OR REPLACE FUNCTION Get_Airports_in_Country(countryCode TEXT) 
RETURNS TABLE(gid int, iko text, name text) AS $$
 DECLARE
    cntry_geom cntry02.the_geom%TYPE;       
 BEGIN   
    SELECT the_geom INTO cntry_geom from cntry02 where iso_2digit = $1;

    RETURN QUERY
    SELECT gid, iko, name
      FROM airport
     WHERE ST_Within(the_geom, cntry_geom);
 END;
$$
LANGUAGE plpgsql;

SELECT Get_Airports_in_Country('CA');

I am using PostgreSQL 8.4.

Any idea what I am missing here?


It might look like this:

CREATE OR REPLACE FUNCTION get_airports_in_country(text)
RETURNS TABLE(gid int, iko text, name text) AS $x$
DECLARE
-- $1 .. countryCode text   -- just one way to comment
   cntry_geom cntry02.the_geom%TYPE;       
BEGIN

cntry_geom := c.the_geom FROM cntry02 c WHERE c.iso_2digit = $1;

RETURN QUERY
SELECT a.gid, a.iko, a.name
  FROM airport a
 WHERE ST_Within(a.the_geom, cntry_geom);

END;
$x$
LANGUAGE plpgsql;

Call:

SELECT * FROM get_airports_in_country('CA');

Major points:

  • There is not much use in defining names for IN parameters that you are going to reference by number anyway. Leads to unnecessary naming conflicts. Add a comment instead, in such a case.
  • A naming conflict is your core problem. As you use the names gid, iko, namereuse as OUT parameters (in the RETURNS TABLE..), you have to qualify the identical column names in the function body. -> a.gid, a.iko, a.name. PostgreSQL 9.1 is stricter about that stuff and throws errors. Would have helped you, but you run on 8.4.
  • No point in using mixed case identifiers in postgres, as long as you don't double quote them. (It's not wrong, though.)
  • This is called a function or stored procedure. The closest thing to a "PL/pgSQl script" would be the "anonymous code block" of a DO statement, introduced in PostgreSQL 9.0.


you should to use a different query

SELECT * FROM Get_Airports_in_Country('CA');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜