简体   繁体   中英

Concatenate variable into dynamic SELECT statement in PL/pgSQL

I want to use a variable in a dynamic SELECT statement (that is in an EXECUTE statement) like this:

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;

I have a variable _some_condition integer := 50; and I want to concatenate its value into the SELECT statement ( ...WHERE factors.condition = _some_condition; ) however this is giving me a "column does no exist" error:

 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 

Why am I getting this error and how to fix this? Keep in mind I have to use a dynamic SELECT statement.

Since you are trying to pass a value (which is not the same as a literal , btw), all you need is the USING clause of the plpgsql EXECUTE command , like @Craig commented .

While being at it, simplify your function with RETURN QUERY EXECUTE :

CREATE OR REPLACE FUNCTION get_factor()
  RETURNS TABLE(factor numeric) AS
$func$
DECLARE
   _some_condition integer := 50;
BEGIN
   RETURN QUERY EXECUTE 
      'SELECT factor_material
       FROM   factors
       WHERE  condition = $1'
   USING _some_condition;
END
$func$ LANGUAGE plpgsql;

Nothing in this example requires dynamic SQL. You could just:

RETURN QUERY
SELECT f.factor_material
FROM   factors f
WHERE  f.condition = _some_condition;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM