postgresql 我如何输出存储在声明的::text[]中的所有ID

mrphzbgm  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(175)

我正在尝试批量插入复制的记录,以便对应用程序进行压力测试。

DO $$
DECLARE
    f text[];
BEGIN
    FOR counter IN 1..5 LOOP
        WITH success_insert AS (
            WITH appointment AS (
                SELECT * FROM scheduler_appointments LIMIT 1
            )
            INSERT INTO scheduler_appointments (id, schedule_id, call_id, identifier, name, starts_at, ends_at, created_at, updated_at, type_id)
            SELECT gen_random_uuid(), schedule_id, call_id, gen_random_uuid(), 'TEST FROM MASS PGSQL', starts_at, ends_at, now(), now(), type_id
            FROM appointment
            RETURNING id
        )
        SELECT array_agg(id) INTO f FROM success_insert;
    END LOOP;
    
    SELECT * FROM unnest(f);
END; $$

然而,我似乎不能得到一个列表的所有ID的地方创建。我反而收到以下错误:
错误:查询没有结果数据的目标

6yoyoihd

6yoyoihd1#

最后一个语句SELECT * FROM unnest(f);没有INTO子句。我假设目的是返回所有插入的id s;但是,当最后一条语句运行时,f将只具有最后一次通过循环的id。不需要使用PLPGSQL。下面的SQL将生成scheduler_appointments并返回id的数组:

WITH appointment AS (
  SELECT * FROM scheduler_appointments LIMIT 1
),
success_insert AS (
  INSERT INTO scheduler_appointments (id, schedule_id, call_id, identifier, name, starts_at, ends_at, created_at, updated_at, type_id)
  SELECT gen_random_uuid(), schedule_id, call_id, gen_random_uuid(), 'TEST FROM MASS PGSQL', starts_at, ends_at, now(), now(), type_id
    FROM appointment CROSS JOIN generate_series(1,5) s(counter)
    RETURNING id
)
SELECT array_agg(id)
  FROM success_insert;

相关问题