Search code examples
postgresqlconcatenationplpgsqldynamic-sql

concatenate additional text to string variable in pl/pgsql


I am using pl/pgsql and I am trying to do somehting like myvar+="additional text"

This is what I do

mywhere := 'dyn_tab2.id=$1';
IF fk IS NOT NULL
THEN
mywhere := mywhere || "AND dyn_tab2.fk_id=$2";
END IF;

So, I want the final mywhere to be dyn_tab2.id=$1 AND dyn_tab2.fk_id=$2, but I get the following error

ERROR:  column "AND dyn_tab2.fk_id=$2" does not exist
LINE 1: SELECT mywhere || "AND dyn_tab2.fk_id=$2"
                          ^
QUERY:  SELECT mywhere || "AND dyn_tab2.fk_id=$2"
CONTEXT:  PL/pgSQL function __aa(integer,integer) line 12 at assignment
SQL state: 42703

How can I concatenate additional text to an already existing string variable ?

Thank you


Solution

  • You must use single-quotes around your strings and not double-quotes, like so:

    mywhere := mywhere || 'AND dyn_tab2.fk_id=$2';

    Double-quotes are used to indicate an object, like a column.