Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: How to set value to variable using 'execute'?

Tags:

postgresql

I have a query which is assigned to some variable and I want to execute it with setting some values.

Example:

create or replace function funct1(a int)
returns void as
$$
declare
       wrclause varchar := '';
       sqlq varchar ;
       t varchar;
begin
     IF (a IS NOT NULL ) THEN 
        wrclause := 'where C = '|| a ||' AND C IN ('|| a || ')';
     END IF;


     sqlq := ' t :=select string_agg(''select *, abcd as "D" from '' || table_namess  ||, '' Union all '') as namess
     from tablescollection2 ud
     inner join INFORMATION_SCHEMA.Tables so on ud.table_namess = so.Table_name ' || wrclause;

      raise info '%',sqlq;

      execute sqlq; /* How to set value to variable f.ex (t varchar output,t output)*/

      raise info '%',t;
end;
$$
language plpgsql;

In SQL Server: We can use

exec sp_executesql @sqlq, N'@t nvarchar(max) output', @t OUTPUT;

Note: How can I do in the PostgreSQL?

MyTry:

execute sqlq(t varchar output,t output); /* getting error near varchar */
like image 554
Sarfaraz Makandar Avatar asked Feb 17 '26 10:02

Sarfaraz Makandar


1 Answers

You can do something like

EXECUTE sqlq INTO target_variable;

for more help plpgsql-statements

like image 87
Ilesh Patel Avatar answered Feb 19 '26 13:02

Ilesh Patel