将我的函数简化为postgres sql查询

时间:2016-11-30 13:53:01

标签: postgresql function postgis plpgsql

我可以在Postgres中只使用sql来简化这个功能吗? (没有删除,忘了) 我只需要选择并插入查询。

我已尝试使用"递归"没有成功。

CREATE OR REPLACE FUNCTION mt_CriarRotaExecutada(id_rota integer)
  RETURNS void AS
$$
DECLARE
    searchsql text := '';
    searchsqlId text := '';
    var_match RECORD;
BEGIN
    EXECUTE('delete from rota_executada where id_rota = ' || CAST( id_rota As text));
    searchsql := 'select (ST_DumpPoints(the_geom)).geom as the_geom,
                         id_destino 
                  from (select id, the_geom, id_destino 
                        from rota_data 
                        where num =' || CAST( id_rota As text) || 
                        ' order by id) a';

    FOR var_match IN EXECUTE(searchsql) 
    LOOP

        EXECUTE 'insert into rota_executada(id_rota, id_rua, id_destino, the_geom, visitado) 
                 select $1, id, $3, $2,  $4 
                 from ruas r 
                 ORDER BY r.the_geom <#> $2 
                 LIMIT 1' 
        USING id_rota, var_match.the_geom, var_match.id_destino, 'N';
    END LOOP;
END;
$$
LANGUAGE 'plpgsql';

感谢。

1 个答案:

答案 0 :(得分:0)

你不需要EXECUTE只需要执行sql语句

DELETE from rota_executada where id_rota = id_rota::text;

AND

INSERT INTO rota_executada(id_rota, id_rua, id_destino, the_geom, visitado) 
   SELECT id_rota, id, var_match.id_destino, var_match.the_geom,  'N'
   FROM ruas r 
   ORDER BY r.the_geom <#> var_match.the_geom
   LIMIT 1