使用参数作为子选择创建函数

时间:2010-07-05 17:24:29

标签: postgresql function plpgsql

我想创建一个选择和更改数据的函数

CREATE OR REPLACE FUNCTION PublicatedTask( argument ) RETURNS SETOF task AS $$DECLARE
   f task%ROWTYPE;   
  BEGIN
    FOR f IN SELECT * FROM Task where layer IN $1 and publicationin<>0 ORDER BY id LOOP
      if (f.publicationIN = 1) then
    f.description='';
    end if;    
    RETURN NEXT f; 
    END LOOP;
    RETURN;
  END;
  $$
 LANGUAGE 'plpgsql';

但我不知道什么参数类型?

我想SELECT * FROM PublicatedTask((1,2,3));

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

或使用VARIADIC

CREATE OR REPLACE FUNCTION PublicatedTask( VARIADIC argument int[]) RETURNS SETOF task AS $$DECLARE
   f task%ROWTYPE;   
  BEGIN
    FOR f IN SELECT * FROM Task where layer = ANY($1) and publicationin<>0 ORDER BY id LOOP
      if (f.publicationIN = 1) then
    f.description='';
    end if;    
    RETURN NEXT f; 
    END LOOP;
    RETURN;
  END;
  $$
 LANGUAGE 'plpgsql';

并以这种方式使用它:

SELECT * FROM PublicatedTask(1,2,3);
从版本8.4开始,

VARIADIC可用:http://www.postgresql.org/docs/8.4/interactive/xfunc-sql.html#XFUNC-SQL-VARIADIC-FUNCTIONS

答案 1 :(得分:0)

您可以使用整数数组作为参数:

CREATE OR REPLACE FUNCTION PublicatedTask( argument int[]) RETURNS SETOF task AS $$DECLARE
   f task%ROWTYPE;   
  BEGIN
    FOR f IN SELECT * FROM Task where layer = ANY($1) and publicationin<>0 ORDER BY id LOOP
      if (f.publicationIN = 1) then
    f.description='';
    end if;    
    RETURN NEXT f; 
    END LOOP;
    RETURN;
  END;
  $$
 LANGUAGE 'plpgsql';

然后你可以这样称呼它:

SELECT * FROM PublicatedTask('{1,2,3}');