# `Sp_Calc_sMad` (procedure)

> 材料调拨


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

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `iFlag` | `int` |
| 2 | IN | `iTmpCheck` | `int` |
| 3 | IN | `sFormGuid` | `varchar(100)` |
| 4 | IN | `sGuid` | `varchar(100)` |
| 5 | IN | `sLoginId` | `varchar(100)` |
| 6 | OUT | `sReturn` | `varchar(1000)` |
| 7 | IN | `sBrId` | `varchar(100)` |
| 8 | IN | `sSuId` | `varchar(100)` |
| 9 | OUT | `sCode` | `int` |

## Body

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

## Narrative

**Business context:** 材料库存 → 材料库单据 → 材料调拨单据 — material-adjust/transfer check / uncheck on `MitMaterialsAdjustMaster` (COMMENT `'材料调拨'`). 材料调拨 is the inter-warehouse / inter-batch material movement bill: on approval it deducts stock from the source location/batch, credits the destination, posts paired movement rows on `EleMaterialsStock`/`MitMaterialsStore`, and re-checks the stock limits on both sides.

**What it does:** Validates `sGuid`. Opens cursors over `MitMaterialsAdjustSlave` rows to: `Update EleMaterialsStock` (source qty down / destination qty up — paired updates), `INSERT INTO EleMaterialsStock` + `EleMaterialsStock_master` to spawn the destination batch row when it does not yet exist, `INSERT INTO MitMaterialsStore` to log both directions of the movement, `Update MitMaterialsAdjustMaster` to set the audit flags, `Update purpurchaseinstoreslave` to back-write any linked source-purchase slaves; calls `Sp_System_AutoMaterialsPriceSingle` to refresh weighted prices, `Sp_calc_materialsstoreLimit` to re-evaluate min/max stock alerts, with `SysLocking` taken on the warehouses. Uncheck reverses each posting.

**Invocation:** Bound to `gdsmodule.sProcName` on two modules:
- `材料调拨单据` (sId `192116810113315231655092270`) — 材料库存 → 材料库单据 (main desktop form)
- `材料调拨(出)` (sId `192116810111915065794192709`) — 通用常量 root (alternate split-form variant)

Dispatched by Java `BusinessBaseServiceImpl.getPrcName(...)` on the audit/un-audit button. xly-src ships `script/标版/30100101/Sp_Calc_sMad.sql` (install) and `script/标版/optimize/Sp_Calc_sMad.sql` (patch); sibling `Sp_Check_sMad.sql` provides the parallel pre-save validation.
