Passando a tabela como um parâmetro
Eu tenho que converter de lat e long parageom
para usar o PostGIS. Meu problema, tenho várias tabelas de locais diferentes e quero passar a tabela como um parâmetro para a função. Estou tentando isso:
CREATE or REPLACE FUNCTION convert_from_lon_lat(float,float,character varying)
RETURNS integer AS $
select id from $3 as vertices
order by vertices.geom <-> ST_SetSrid(ST_MakePoint($1,$2),4326) LIMIT 1;
$ LANGUAGE SQL;
mas eu recebo um erro de sintaxe.
EDIT1:
Então eu mudei o código anterior para isso:
CREATE or REPLACE FUNCTION convert_from_lon_lat(long float, lat float, _table character varying) RETURNS integer AS $
BEGIN
EXECUTE('select id from _table as vertices order by vertices.geom <-> ST_SetSrid(ST_MakePoint(long,lat),4326) LIMIT 1;');
END;
$ LANGUAGE plpgsql;
ele cria sem nenhum problema, mas quando eu chamo de `convert_from_lon_lat (long1, long2, my_table)
Recebo e erro:
ERROR: relation "_table" does not exist
Não está passando o nome da tabela como argumento
EDIT 2:
CREATE or REPLACE FUNCTION convert_from_lon_lat(long float, lat float, tbl character varying) RETURNS integer AS $func$
BEGIN
EXECUTE format('select id from %s order by %s.the_geom <-> ST_SetSrid(ST_MakePoint('|| long || ','|| lat ||'),4326) LIMIT 1;', tbl, tbl);
END;
$func$ LANGUAGE plpgsql;
Agora, quando chamo a função, recebo um `ERROR: control atingiu o final da função sem RETURN``
eu tenteiRETURN QUERY EXECUTE format('...
mas eu recebo umERROR: cannot use RETURN QUERY in a non-SETOF function