1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PostgreSQL】n個の引数を受け取るFunctionを作りたい

Posted at

作りたいもの

任意の数の引数を受け取る事ができるFunction
いわゆる「可変長引数」というやつ

-- 引数すべてを足した値を返却する 
SELECT custom_sum(10, 20, 30, 40, 50);
  --> 300

作り方

引数に「VARIADIC」をつけることで実現できる。

CREATE OR REPLACE FUNCTION custom_sum(VARIADIC nums bigint[])
RETURNS bigint AS $$
DECLARE
	l_num bigint;
	l_ret bigint = 0;
BEGIN
    FOREACH l_num IN ARRAY nums LOOP
        l_ret := l_ret + l_num;
    END LOOP
	;

    RETURN l_ret;
END;
$$ LANGUAGE plpgsql
;

これで何個でも*引数を受け取れる。

SELECT custom_sum(1,2,3,4,5);
--> 15

SELECT custom_sum(1,2,3,4,5,6,7,8,9,10);
--> 55

「何個でも」と言いつつも、引数数の上限(FUNC_MAX_ARGS)まで。

以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?