Postgres嵌套查询执行Insert
DO $$
DECLARE
row RECORD;
price_column TEXT;
BEGIN
FOR row IN
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'cus_tyq_price_20250411'
AND column_name NOT IN ('名称','国家码','型号','分类')
AND table_schema = 'public' -- 添加schema限制确保找到正确的表
LOOP
price_column := row.column_name;
-- 使用动态SQL来引用变量列名
EXECUTE format('
INSERT INTO "public"."product_pricelist_item"
("pricelist_id", "currency_id", "product_tmpl_id", "create_uid",
"write_uid", "applied_on", "base", "compute_price",
"min_quantity", "fixed_price")
SELECT
c.id as pricelist_id,
c.currency_id,
b.id as product_tmpl_id,
2 as create_uid,
2 as write_uid,
''3_global'' as applied_on,
''list_price'' as base,
''fixed'' as compute_price,
1 as min_quantity,
a.%I::numeric as fixed_price
FROM
"public"."cus_tyq_price_20250411" a
LEFT JOIN "public"."product_template" b
ON a."名称" = b.name->>''zh_CN''
AND a."型号" = b.specification
LEFT JOIN "public"."product_pricelist" c
ON c.name->>''zh_CN'' = %L
WHERE
a.%I IS NOT NULL
AND b.id IS NOT NULL
AND c.id IS NOT NULL',
price_column, price_column, price_column);
RAISE NOTICE '已处理价格列: %', price_column;
END LOOP;
END $$;
评论区