开发者

How do I pass in the array output of SQL query into a PostgreSQL (PL/pgSQL) function?

I am able to do the following in SQL where an "array" of user_ids are passed into the where clause of a SQL query.

select * from users where id in (select user_id from profiles);

I would like to do the same thing but pass the "array" into a PostgreSQL (PL/pgSQL) function as shown below. How do I declare the function and work with the "array" within the function?

select * from users_function(select user_id from profiles);

CREATE OR REPLACE FUNCTION users_function(....)
  RETU开发者_开发问答RNS void AS
$BODY$
....


Declare an array datatype [] in the function then use the aggregate function array_agg to transform the select statement into an array.

CREATE OR REPLACE FUNCTION users_function(myints integer[])
$$
 BEGIN
      -- you need to find the bounds with array_lower and array_upper
  FOR i in array_lower(myints, 1) .. array_upper(myints, 1) LOOP
     Raise Notice '%', myints[i]::integer;
  END LOOP;
 END;
$$

select * from users_function(array_agg((select user_id from profiles)));


I could not get the nate c's array_agg approach as I described above. This is an option:

select * from test_array('{1,2}');

CREATE OR REPLACE FUNCTION test_array(user_ids integer[])
  RETURNS void AS
$$
declare
begin
FOR i in array_lower(user_ids, 1) .. array_upper(user_ids, 1) LOOP
  RAISE NOTICE '%', user_ids[i]::integer;
END LOOP;
end
$$
LANGUAGE plpgsql;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜