使用ID数组将记录插入表中(如果它尚不存在)

时间:2018-03-02 23:17:56

标签: postgresql psql

我创建了一个postgresql函数,它以逗号分隔的id列表作为输入参数。然后我将这个以逗号分隔的列表转换为数组。

CREATE FUNCTION myFunction(csvIDs text)
RETURNS void AS $$
DECLARE ids INT[];
BEGIN
 ids = string_to_array(csvIDs,',');

  -- INSERT INTO tableA

END; $$
LANGUAGE PLPGSQL;

我现在要做的是,如果表中没有ID,则将每个id(在数组中)的记录插入到表A中。新记录的值字段应设置为0。

表格就是这样创建的

CREATE TABLE TableA (
    id int PRIMARY KEY,
    value int
);

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用unnest()函数获取数组的每个元素。

create table tableA (id int);
insert into tableA values(13);
select t.ids
from  (select unnest(string_to_array('12,13,14,15', ',')::int[]) ids) t
| ids |
| --: |
|  12 |
|  13 |
|  14 |
|  15 |

现在,您可以在插入新行之前检查ids值是否存在。

CREATE FUNCTION myFunction(csvIDs text)
RETURNS int AS 
$myFunction$
DECLARE
    r_count int;
BEGIN

    insert into tableA
    select t.ids
    from   (select unnest(string_to_array(csvIDs,',')::int[]) ids) t
    where  not exists (select 1 from tableA where id = t.ids);
    GET DIAGNOSTICS r_count = ROW_COUNT;
    return r_count;

END; 
$myFunction$
LANGUAGE PLPGSQL;
select myFunction('12,13,14,15') as inserted_rows;
| inserted_rows |
| ------------: |
|             3 |
select * from tableA;
| id |
| -: |
| 13 |
| 12 |
| 14 |
| 15 |

dbfiddle here

相关问题