# `Sp_beforeSave_sMpa` (procedure)

> 领料申请存前反写数量


- **Type:** PROCEDURE
- **Deterministic:** NO
- **SQL data access:** CONTAINS SQL

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `sGuid` | `varchar(2000)` |
| 2 | IN | `sBrId` | `varchar(100)` |
| 3 | IN | `sSuId` | `varchar(100)` |
| 4 | OUT | `sCode` | `int` |
| 5 | OUT | `sReturn` | `varchar(4000)` |

## Body

_Body is not pre-cached. To inspect: `mysql --defaults-file=~/.my.cnf -e 'SHOW CREATE PROCEDURE `Sp_beforeSave_sMpa`'`._

## Narrative

**Business context:** 生产执行 / MES单据 / 领料申请单据 (also 补料申请单据, 补版申请单据) — before-save handler that re-aggregates the MES picking-application totals onto the upstream `MftWorkOrderMaterials` work-order BOM lines so applied/auxiliary quantities stay consistent before the master save commits. Comment header: `领料申请存前反写数量`.

**What it does:** Builds a dynamic UPDATE: re-sums `dAuxiliaryQty` and `dMaterialsQty` from `mitproductionapplySlave` (excluding the current `sGuid` set, only `bInvalid=0` masters) grouped by `sSrcSlaveId`, then writes the totals into `MftWorkOrderMaterials.dProductionApplyAuxiliaryQty` and `.dProductionApplyQty` for the touched BOM rows, scoped by `sBrandsId` / `sSubsidiaryId`. The SQL is then split by `;` and executed via `PREPARE` / `EXECUTE` / `DEALLOCATE`.

**Invocation:** Hooked as `gdsmodule.sSaveProNameBefore` on 3 modules — `领料申请单据` (sId `101251240115016056026128440`), `补料申请单据` (`12012615914116395420093200`), `补版申请单据` (`12012615914116395420566910`). Also called by dispatcher procs `Sp_Invalid_backwriting` and `Sp_delete_backwriting` to replay the writeback on invalidate/delete. Install script: `xly-src/script/标版/30100101/Sp_beforeSave_sMpa.sql`.

Flag: the body still contains a stray `SELECT @sSqlStmt;` inside the prepared-statement loop — emits a debug result-set on every save.
