侧边栏壁纸
博主头像
EinTao博主等级

昨天再好,也走不回去;明天再难,也要抬脚继续。

  • 累计撰写 32 篇文章
  • 累计创建 3 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

Postgres嵌套查询执行Insert

EinTao
2025-04-15 / 0 评论 / 0 点赞 / 10 阅读 / 312 字

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 $$;
0

评论区