Postgresql在函数内执行动态查询返回NULL

时间:2015-10-29 14:55:15

标签: sql postgresql function plpgsql

我有一个Postgresql函数,它将获得一些输入(动态查询从这些参数中查询值)并返回值(在这里它是唯一的,因此结果应该是一个整数)。

但是,我可以通过终端正常查询动态(很容易从表中选择id ='abcd'的值)并获取值(例如:2)。但是当我执行该函数时,Executed动态查询的值总是返回NULL。

我该如何解决这个问题?当我不知道为什么EXECUTE“查询”INTO变量但变量返回NULL而“查询”可以在另一个终端中运行时返回值时,它很累。

这是我的函数,我想返回_result_value(它总是NULL - 注意:结果ABC :)。当我可以通过psql查询。

SELECT uom_id FROM ps_quantity WHERE id = 15
 uom_id 
--------
      1
(1 row)




   CREATE OR REPLACE FUNCTION select_field(
    selected_table text,
    selected_field text,
    field_type_sample anyelement,
    where_clause text DEFAULT ''::text)
  RETURNS anyelement AS
$BODY$DECLARE
    -- Log
    ME  constant text := 'selected_field()';
    -- Local variables
        _qry          text;
        _result_value ALIAS FOR $0;
    abc integer := 0;
    BEGIN
    RAISE NOTICE 'FUNCTION select_field';
       --- _qry := 'SELECT ' || quote_ident(selected_field) ||
       ---          ' FROM ' || quote_ident(selected_table) ||
       ---               ' ' || where_clause;

    _qry := ' SELECT uom_id FROM ps_quantity WHERE id = 15; ';

    RAISE NOTICE 'WHAT IN HERE: query %', _qry;

       -- return 1000;              
       -- RAISE DEBUG '%: %', ME, _qry;
    RAISE NOTICE 'Preparing to query data';
       -- EXECUTE _qry INTO  _result_value; 
        --EXECUTE (' SELECT uom_id FROM ps_quantity WHERE id = ''15'' ') into abc;
    EXECUTE ' SELECT uom_id FROM ps_quantity WHERE id = 15; ' into _result_value;
    RAISE NOTICE 'RESULT ABC: %', _result_value;



        RETURN  _result_value;
    END;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

1 个答案:

答案 0 :(得分:0)

Your code is working on my database. Maybe you are executing different instance of this function - PostgreSQL allows function overloading, and some mysterious bugs are based on more functions with same name.

I am pretty dislike this kind of functions - you try to hide SQL - and the usual result if this technique is pretty slow applications, but it is your life :). With modern PostgreSQL you can write your function little bit more readable:

CREATE OR REPLACE FUNCTION foo(_field text, _table text, _id int,
                               resulttypedval anyelement, OUT _result anyelement)
AS $$
BEGIN
  EXECUTE format('SELECT %I FROM %I'
                      ' WHERE $1 IS NULL OR id = $1',
                  _field, _table)
     INTO _result
     USING _id;
  RETURN;
END;
$$ LANGUAGE plpgsql;