将变量连接到PL / pgSQL中的动态SELECT语句中

时间:2015-08-17 09:20:17

标签: sql postgresql plpgsql dynamic-sql

我想在动态SELECT语句中使用变量(在EXECUTE语句中),如下所示:

CREATE OR REPLACE FUNCTION get_factor()
  RETURNS TABLE(factor numeric) AS
$BODY$
DECLARE
    _query character varying;
    _some_condition integer := 50;
    _result decimal;
BEGIN
    _query := 'SELECT factors.factor_material FROM factors
               WHERE factors.condition = _some_condition;';

    EXECUTE _query INTO _result;

    RETURN QUERY SELECT _result;
END;

我有一个变量_some_condition integer := 50;,我想将它的值连接到SELECT语句(...WHERE factors.condition = _some_condition;)但是这给了我一个“列不存在”的错误:

ERROR:  column "_some_condition" does not exist
LINE 1: ...erial WHERE factors.city_id = _some_cond...
                                         ^

CONTEXT:  PL/pgSQL function get_factor() line 12 at EXECUTE statement

为什么我收到此错误以及如何解决此问题?请记住,我必须使用动态SELECT语句。

0 个答案:

没有答案