如何处理postgresql中数组为空的情况?

时间:2015-11-15 06:04:08

标签: sql postgresql

我有一个用plpythonu编写的函数。

CREATE OR REPLACE FUNCTION temp(t_x integer[])
  RETURNS void AS
$BODY$
.
.
.
x=plpy.execute("""select array_to_string(select id from A where id=any(array%s) ), ',')"""%t_x)

在t_x为空的某些情况下,我收到错误:

  

错误:无法确定空数组的类型

我该如何解决?

2 个答案:

答案 0 :(得分:4)

if-else statement

伪代码:

if t_x is empty
  x=null
else
  x=plpy.execute....

铸造

x=plpy.execute("""select array_to_string(select id from A where id=any(array%s::integer[]) ), ',')"""%t_x)

为何投出帮助?

postgres=# select pg_typeof(array[1,2]);
 pg_typeof 
-----------
 integer[]

array[1,2]的类型为integer[]

postgres=# select array[];
ERROR: cannot determine type of empty array
LINE 1: select array[];

array[]没有类型。

postgres=# select pg_typeof(array[]::integer[]);
 pg_typeof 
-----------
 integer[]

array[]::integer[]的类型为integer[]

答案 1 :(得分:0)

也许这可以在将来帮助某人。 在这种情况下,表函数可能会收到NULL或Empty Array(等同于ALL):

CREATE OR REPLACE FUNCTION temp(t_x integer[])
RETURNS void AS
$BODY$
.
.
.
x=plpy.execute("""select array_to_string(select id from A where id=any(array%s) or cardinality(coalesce(array%s,array[]::integer[])) = 0), ',')"""%t_x)