Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass text parameter to stored function for `IN` operator

I need obtain table names from schema, except some tables

CREATE OR REPLACE FUNCTION  func(unnecessary_tables TEXT)
returns void
as $$
begin
      EXECUTE 'SELECT table_name FROM information_schema.tables   
      WHERE 
      table_schema=''public''
      AND 
      table_name NOT IN( $1 )
      ' USING unnecessary_tables

      --here execute retrieved result, etc ...

end;
$$language plpgsql

Then call function

select func('table1'',''table2');

This not works and returns in result table1 and table2 also.

Question is: How to pass text parameter to stored function, for IN operator ?

like image 985
Oto Shavadze Avatar asked Dec 01 '15 12:12

Oto Shavadze


2 Answers

Pass a text array in instead of text:

create or replace function func(unnecessary_tables text[])
returns void as $$
begin
    select table_name
    from information_schema.tables   
    where
        table_schema = 'public'
        and
        not(table_name = any($1))
    ;
end;
$$language plpgsql    

Call it like:

select func(array['t1','t2']::text[]);

BTW the code above can be plain SQL in instead of PL/pgSQL

like image 138
Clodoaldo Neto Avatar answered Oct 12 '22 22:10

Clodoaldo Neto


To answer you exact question (How to pass to function text for IN operator) You need:

SELECT func( '''table1'',''table2''');

The reason is that table names must by string, so they need to by inside quotes. To make it works there is one change in code needed which I did't see at first:

  CREATE OR REPLACE FUNCTION  func(unnecessary_tables TEXT)
returns void
as $$
begin
      EXECUTE 'SELECT table_name FROM information_schema.tables   
      WHERE 
      table_schema=''public''
      AND 
      table_name NOT IN(' || unnecessary_tables || ')'; 

      --here execute retrieved result, etc ...

end;
$$language plpgsql

It's needed because USINGis aware of types and don't just "paste" parameter in place of $1.

like image 26
Gabriel's Messanger Avatar answered Oct 12 '22 21:10

Gabriel's Messanger