PostgreSQL:通过将null值传递给函数</null>来获取<null>字符串

时间:2014-07-10 11:05:16

标签: postgresql

我有一个参数的以下功能。我需要显示一个包含select语句和where条件的字符串。

示例

create or replace function funct(a int)
returns void as
$$
declare
       wrclause varchar := '';
       sqlq varchar ;
       t varchar;
begin
       wrclause := ' AND C IN ('|| a || ')';

       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 where C = '|| a ||'' || wrclause;

       raise info '%',sqlq;

       perform sqlq;

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

调用函数:值为1

select funct(1);

输出

INFO:   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 where C = 1 AND C IN (1)
INFO:  <NULL> 

调用函数:使用空值

select funct(null);

输出

INFO:  <NULL>
INFO:  <NULL> 

注意:在将空字符串分配给wrclause变量之后,我没有收到为什么我收到<NULL>字符串,<NULL>为变量t }。

1 个答案:

答案 0 :(得分:1)

如果满足所有符合NULL的要求,您可以尝试下面的内容:

create or replace function funct(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;

       perform sqlq;

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

select funct(1);

输出:

INFO:   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 where C = 1 AND C IN (1)
INFO:  <NULL>

select funct(null)

INFO:   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
INFO:  <NULL>