1.0.203.sql 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. -- =============================================================================
  2. -- S0-STANDARD-BOM-MATERIAL-FK-BACKFILL-EXECUTION-1
  3. -- 目的:回填 ProductStructureMaster legacy 行(2026-05-27/28 一次性导入只写父/子项编码、
  4. -- 未写后加的 FK 列)的 ParentMaterialId / ComponentMaterialId,按 工厂 + 租户 限定
  5. -- 1:1 关联 ItemMaster.RecID(ItemMaster 唯一索引 uk_ItemMaster_factory_item=(factory_ref_id,ItemNum)
  6. -- 保证工厂内编码唯一 → 无多匹配)。
  7. -- 范围:仅 UPDATE FK IS NULL 的行;只写 FK,不改 ParentItem/ComponentItem 编码、不改 ItemMaster、
  8. -- 不改状态字段(IsActive/IsEnabled)、不删行;不覆盖已有非 NULL FK;不更新 demo RecID=1
  9. -- (其 FK=0 非 NULL,IS NULL 不命中,且 RecID<>1 显式排除)。
  10. -- 安全:工厂限定(p.FactoryRefId=im.factory_ref_id) + 租户限定(p.tenant_id=im.tenant_id);
  11. -- 阶段 0 只读校验:父/子各 53031 行可回填,多匹配 0,匹配不到 0,跨工厂/跨租户 0。
  12. -- 幂等:WHERE FK IS NULL → 重跑只命中剩余 NULL,已回填行不再变动。
  13. -- 回滚(如需,人工执行,非本脚本自动):
  14. -- UPDATE ProductStructureMaster SET ParentMaterialId=NULL, ComponentMaterialId=NULL
  15. -- WHERE RecID<>1 AND CreatedAt BETWEEN '2026-05-27' AND '2026-05-28 23:59:59';
  16. -- =============================================================================
  17. -- 段 1:回填父项 ParentMaterialId
  18. UPDATE ProductStructureMaster p
  19. JOIN ItemMaster im
  20. ON im.ItemNum = p.ParentItem
  21. AND im.factory_ref_id = p.FactoryRefId
  22. AND im.tenant_id = p.tenant_id
  23. SET p.ParentMaterialId = im.RecID
  24. WHERE p.ParentMaterialId IS NULL
  25. AND p.ParentItem IS NOT NULL
  26. AND p.ParentItem <> ''
  27. AND p.RecID <> 1;
  28. -- 段 2:回填子项 ComponentMaterialId
  29. UPDATE ProductStructureMaster p
  30. JOIN ItemMaster im
  31. ON im.ItemNum = p.ComponentItem
  32. AND im.factory_ref_id = p.FactoryRefId
  33. AND im.tenant_id = p.tenant_id
  34. SET p.ComponentMaterialId = im.RecID
  35. WHERE p.ComponentMaterialId IS NULL
  36. AND p.ComponentItem IS NOT NULL
  37. AND p.ComponentItem <> ''
  38. AND p.RecID <> 1;