0

I have a string to execute with the string aggregate function within the postgresql function. Here is the following script for that.

Example:

create or replace function f(colvalue int,colnvalue varchar)
returns void as
$$
declare
      sql varchar;
      var varchar;
begin
     sql := 'Select var:= string_agg(................) /* Error occurred here near var:= */
             from tablename where cola ='|| colvalue || ' AND coln ='|| colnvalue;

     raise notice '%'sql;

     execute sql into var;

     raise notice var;

end;
$$
language plpgsql;

Error:

ERROR:  syntax error at or near ":="

Note: I want the result of string_agg into var.

1 Answer 1

2

Dynamic SQL can contains SQL statement only - but ":=" is a PL/pgSQL statement. Next, it is clean from your example, so it is useless there. Second issue is a SQL injection vulnerability (still this code should not work). Newer use a patter ' || varcharvar || ' for SQL used in dynamic SQL.

CREATE OR REPLACE FUNCTION f(colvalue int,colnvalue varchar)
RETURNS void AS $$
DECLARE
  sql varchar;
  var varchar;
BEGIN
  sql := 'SELECT string_agg(..) FROM tablename WHERE cola=$1 AND coln=$2';
  RAISE NOTICE '%', sql;
  EXECUTE sql INTO var USING colvalue, colnvalue;
  RAISE NOTICE '%', var;
END;
$$ LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. But getting <NULL> string in var variable. :(
Yeah! I Solved it. Thank you so much for your valuable assistance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.