在 Postgresql 中批量插入

Bulk Insert in PostgresSql

你好,我有这个简单的插入语句

insert into location_access (employee,location,permissionid)
values
(empID,8241,4),
(empID,8260,4),
(empID,8269,4),
(empID,8261,4),
(empID,8170,4),
(empID,7908,4),
(empID,8008,4),
(empID,8026,4),
(empID,8029,4),
(empID,8242,4),
(empID,8270,4),
(empID,8278,4),
(empID,8279,4),
(empID,8281,4),
(empID,8284,4),
(empID,8288,4),
(empID,8171,4),
(empID,7909,4),
(empID,8156,4),
(empID,7258,4),
(empID,8027,4)

对于 empiD,我还有一个包含 190 多个 employeeID 的列表 所以对这些值进行硬编码会很痛苦有没有更好的方法来做到这一点可能是一个“循环” 循环所有员工 ID 并将它们添加到每个位置?

示例员工 ID

41743
41746
41753
43554
43557
43561
43563
43568
43569
43570
43572
43573
43574
43576
43577
43579
43582
43584  

使用For循环,可以插入多条记录

DO
$do$
DECLARE
   a integer[] := array[41743,41746,41753,43554,43557,43561,43582,43584 ];
   i integer;                   
BEGIN
   FOR i IN 1 .. array_upper(a, 1)
   LOOP
      RAISE NOTICE '%', a[i];      -- single quotes
      insert into location_access (employee,location,permissionid)
values
(a[i],8241,4);
   END LOOP;
END
$do$;

这是演示https://extendsclass.com/postgresql/ecb3b7c

您可以交叉加入员工 ID 列表:

insert into location_access (employee,location,permissionid)
select source.employee, source.location, source.permissionid
from (
 values
   (41743),(41746),(41753),(43554),(43557),(43561),
   (43563),(43568),(43569),(43570),(43572),(43573),
   (43574),(43576),(43577),(43579),(43582),(43584)
) as emp(empid) 
  cross join lateral (
    values 
      (emp.empid,8241,4),
      (emp.empid,8260,4),
      (emp.empid,8269,4),
      (emp.empid,8261,4),
      (emp.empid,8170,4),
      (emp.empid,7908,4),
      (emp.empid,8008,4),
      (emp.empid,8026,4),
      (emp.empid,8029,4),
      (emp.empid,8242,4),
      (emp.empid,8270,4),
      (emp.empid,8278,4),
      (emp.empid,8279,4),
      (emp.empid,8281,4),
      (emp.empid,8284,4),
      (emp.empid,8288,4),
      (emp.empid,8171,4),
      (emp.empid,7909,4),
      (emp.empid,8156,4),
      (emp.empid,7258,4),
      (emp.empid,8027,4)
   ) as source(employee,location,permissionid)