开发者

PostgresQL: Loop over integer[] and insert current element into another table

I have a function which takes a parameter named p_categories, of type smallint[].

How do I look through p_categories and execute the following command, where cat is the current smallint in p_categories?

INSERT INTO mytable (i_category) VALUES (cat)

Something like this (pseudocode) maybe?

FOR cat in SELECT p_categories
    INSERT INTO mytable (i_category) VALUES (cat)
END LOOP;

That gives me an error: "invalid input syntax for integer: "{开发者_高级运维14,20}" when p_categories is '{14,20}'.


I think you're looking for unnest

INSERT INTO mytable (i_category)
SELECT unnest(p_categories);

The unnest array function just expands an array into its elements.

Or a more concrete example:

> create table t (i int not null);
> insert into t (i) select unnest(array[1,2]);
> select * from t;
 i 
---
 1
 2
(2 rows)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜