BEGIN;

CREATE TEMP TABLE part_mng_sync_stage (
  part_no varchar,
  material varchar,
  heat_treatment_hardness varchar,
  heat_treatment_method varchar,
  surface_treatment varchar,
  maker varchar,
  part_type varchar,
  spec varchar,
  acctfg varchar,
  odrfg varchar,
  unit_dc varchar,
  unitmang_dc varchar,
  unitchng_nb varchar,
  lot_fg varchar,
  use_yn varchar,
  qc_fg varchar,
  setitem_fg varchar,
  req_fg varchar,
  unit_length varchar,
  unit_qty varchar
);

\copy part_mng_sync_stage FROM '/tmp/part_mng_sync.csv' WITH CSV HEADER

UPDATE part_mng P SET
  material                = NULLIF(S.material, ''),
  heat_treatment_hardness = NULLIF(S.heat_treatment_hardness, ''),
  heat_treatment_method   = NULLIF(S.heat_treatment_method, ''),
  surface_treatment       = NULLIF(S.surface_treatment, ''),
  maker                   = NULLIF(S.maker, ''),
  part_type               = NULLIF(S.part_type, ''),
  spec                    = NULLIF(S.spec, ''),
  acctfg                  = NULLIF(S.acctfg, ''),
  odrfg                   = NULLIF(S.odrfg, ''),
  unit_dc                 = NULLIF(S.unit_dc, ''),
  unitmang_dc             = NULLIF(S.unitmang_dc, ''),
  unitchng_nb             = CASE WHEN S.unitchng_nb = '' THEN P.unitchng_nb ELSE S.unitchng_nb::numeric END,
  lot_fg                  = NULLIF(S.lot_fg, ''),
  use_yn                  = NULLIF(S.use_yn, ''),
  qc_fg                   = NULLIF(S.qc_fg, ''),
  setitem_fg              = NULLIF(S.setitem_fg, ''),
  req_fg                  = NULLIF(S.req_fg, ''),
  unit_length             = NULLIF(S.unit_length, ''),
  unit_qty                = NULLIF(S.unit_qty, ''),
  is_last                 = COALESCE(P.is_last, '1'),
  edit_date               = NOW()
FROM part_mng_sync_stage S
WHERE P.part_no = S.part_no;

COMMIT;

SELECT
  COUNT(*) AS total,
  COUNT(NULLIF(material,''))   AS material_filled,
  COUNT(NULLIF(acctfg,''))     AS acctfg_filled,
  COUNT(NULLIF(unit_dc,''))    AS unit_dc_filled,
  COUNT(NULLIF(part_type,''))  AS part_type_filled,
  COUNT(NULLIF(spec,''))       AS spec_filled,
  COUNT(NULLIF(maker,''))      AS maker_filled,
  COUNT(NULLIF(is_last,''))    AS is_last_filled
FROM part_mng;

SELECT part_no, material, spec, part_type, acctfg, odrfg, unit_dc, unitmang_dc, unitchng_nb, lot_fg, use_yn, qc_fg, setitem_fg, req_fg
  FROM part_mng WHERE part_no = '000AN003000';
