如果 table 不存在,则使用 ID 数组将记录插入

Use array of IDs to insert records into table if it does not already exist

我创建了一个 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 在 table 中不存在,则将每个 ID(在数组中)的记录插入到 TABLE A 中。新记录的值字段应设置为 0。

Table是这样创建的

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

这可以吗?

您可以使用 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