在postgresql函数中捕获select查询返回值并使用它

时间:2016-04-28 08:38:20

标签: postgresql plpgsql

我想执行此功能。但它有错误说

  

ERROR:

     

语法错误在":="

     

第7行:选择结果:= MAX(path_history_id)作为路径INTO结果来自......

在这个函数中我想:

  1. 执行select with (MAX),它将从表中返回最大ID;
  2. 捕获该值(它是一个整数值);
  3. 将该值放入最后一个选择查询条件。
  4. 我无法在postgresql中找到一种方法来做到这一点。

    CREATE OR REPLACE FUNCTION memcache(IN starting_point_p1 character varying, IN ending_point_p1 character varying)
    
    RETURNS TABLE(path integer, movement_id_out integer, object_id_fk_out integer, path_history_id_fk_out integer, walking_distance_out real, angel_out real, direction_out character varying, time_stamp_out timestamp without time zone, x_coordinate_out real, y_coordinate_out real, z_coordinate_out real) AS
    $BODY$
        DECLARE result int;
        BEGIN
    
        select result:=MAX(path_history_id)as path INTO result from path_history_info where starting_point=starting_point_p1 and ending_point =ending_point_p1 and achieve='1';
        return query
        select * from movement_info where path_history_id_fk=result;    
        END;
        $BODY$
      LANGUAGE plpgsql
    

1 个答案:

答案 0 :(得分:1)

语法错误

您的函数内的第一个查询需要更改如下:

select MAX(path_history_id)as path INTO result 
  from path_history_info 
    where starting_point=starting_point_p1 
     and ending_point =ending_point_p1 and achieve='1';

单个查询

您实际上并不需要存储过程。单个查询可以获得相同的结果。

select * from movement_info where path_history_id_fk = 
 (SELECT MAX(path_history_id) FROM path_history_info 
    where starting_point=starting_point_p1 
     and ending_point =ending_point_p1 and achieve='1';