Postgresql函数用于动态传递参数

时间:2018-02-12 07:51:08

标签: sql postgresql function procedural

我创建了一个函数abcd_insert(),它将数据插入到表abcd中,该表有8列。函数内部的代码类似于下面的代码:

BEGIN  
 INSERT INTO abcd

 VALUES 
      (
    x                 ,
    y                 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a3 = 1 union all select count(*) from b where b1 = x and b2 = y and b3 = 1 ) as n1,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 2 union all select count(*) from b where b1 = x and b2 = y and b3 = 2 ) as n2 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 3 union all select count(*) from b where b1 = x and b2 = y and b3 = 3 ) as n3 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 4 union all select count(*) from b where b1 = x and b2 = y and b3 = 4 ) as n4 ,
    select sum(count) from (select count(*) from a where a1 = x and a2 = y and a2 = 5 union all select count(*) from b where b1 = x and b2 = y and b3 = 5 ) as n5 ,
    SELECT sum(q1) from
    (SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END as q1 FROM p1 where p11 = x and p12 = y union all
    SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END as q1 FROM p2 where p21 = x and p22 = y )  as q1
  ); 
END; 

'x'和'y'是我的输入参数,其值将传递给函数abcd_insert()。 a,b,p1和p2是同一模式中的表。 当我在运行时将'x'和'y'传递给函数时,它会抛出错误。 有人可以告诉我这里我做错了什么。

2 个答案:

答案 0 :(得分:0)

我认为您最好在insert语句中指定列名。

Insert into abcd ("column1",...,"column8") values ...

请发布错误,以便其他人可以提供帮助。

答案 1 :(得分:0)

使用示例代码,您需要围绕查询括号,因此您将使用其结果,例如:

t=# create table t (i int, e int);
CREATE TABLE
t=# create or replace function f(x int) returns void as $$
begin
 insert into t values (x, (select 1 where x > 0));
end;
$$ language plpgsql;
CREATE FUNCTION
t=# select f(1);
 f
---

(1 row)

t=# select * from t;
 i | e
---+---
 1 | 1
(1 row)