0

我创建了如下函数:

CREATE TYPE points AS (
    "gid" double precision
  , "elevation" double precision
  , "distance" double precision
  , "x" double precision
  , "y" double precision
);    

CREATE OR REPLACE FUNCTION public.nd_test4()
RETURNS  SETOF points AS $$

DECLARE     
    sql text;
    rec points;             
BEGIN       
    sql := 'select
        "gid"
        , "elev" as "elevation"
        , st_distance(ST_MakePoint(1093147, 1905632) , "the_geom" ) as "distance"
        , st_x("the_geom") as "x"
        , st_y("the_geom")as "y"
    from
        "elevation-test"
    where
        st_within("the_geom" ,st_buffer(ST_MakePoint(1093147, 1905632), 15) )
    order by distance limit 4';

    FOR rec IN EXECUTE(sql) LOOP
        RETURN NEXT rec;

    END LOOP;                                   
END;
    $$ LANGUAGE plpgsql VOLATILE;

当我运行类似的函数时select nd_test4();,我得到的结果没有像下面这样的文件名。

图片?

我怎样才能得到这样的文件名的结果:

gid | elevation | distance | x       | y
----+-----------+----------+---------+-------
 1  | 350.0     | 10       | 12345.1 | 12435 
4

1 回答 1

1

调用函数:

SELECT * FROM nd_test4();

此外,您的函数定义是不必要的复杂。简化为:

CREATE OR REPLACE FUNCTION public.nd_test4()
  RETURNS SETOF points AS
$func$
BEGIN

RETURN QUERY
SELECT gid
      ,elev           -- AS elevation
      ,st_distance(ST_MakePoint(1093147, 1905632) , the_geom ) -- AS distance
      ,st_x(the_geom) -- AS x
      ,st_y(the_geom) -- AS y
FROM   "elevation-test"
WHERE  st_within(the_geom, st_buffer(ST_MakePoint(1093147, 1905632), 15))
ORDER  BY distance
LIMIT  4;

END
$func$ LANGUAGE plpgsql;

或者更好的是,在这里使用一个普通的 SQL 函数:

CREATE OR REPLACE FUNCTION public.nd_test4()
  RETURNS SETOF points AS
$func$
SELECT gid
      ,elev           -- AS elevation
      ,st_distance(ST_MakePoint(1093147, 1905632) , the_geom ) -- AS distance
      ,st_x(the_geom) -- AS x
      ,st_y(the_geom) -- AS y
FROM  "elevation-test"
WHERE  st_within(the_geom, st_buffer(ST_MakePoint(1093147, 1905632), 15))
ORDER  BY distance
LIMIT  4
$func$ LANGUAGE sql;
  • 无需动态 SQL。

  • 我还去掉了无端的双引号。合法的小写标识符不需要。例外是"elevation-test"。不应将运算符 ( -) 用作表名的一部分。那只是自找麻烦。

  • 函数体中的别名被复合类型的列名替换。它们仅在函数内部可见,因此在您的案例中只是文档。

于 2013-10-16T04:01:55.180 回答