# `Sp_System_AutoMaterialsPriceSingle` (procedure)


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

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `sMaterialsGuid` | `varchar(100)` |
| 2 | IN | `sMaterialsStyleS` | `varchar(100)` |
| 3 | IN | `sDefineNoS` | `varchar(100)` |
| 4 | IN | `sDefineNo2S` | `varchar(100)` |
| 5 | IN | `sWareHouseGuid` | `varchar(100)` |
| 6 | IN | `sLocationGuid` | `varchar(100)` |
| 7 | IN | `sWarehouseLocationGuid` | `varchar(100)` |
| 8 | IN | `tStartDate` | `datetime` |
| 9 | IN | `tEndDate` | `datetime` |
| 10 | IN | `sGuid` | `varchar(100)` |
| 11 | IN | `bUpdate` | `int` |
| 12 | IN | `bFlag` | `int` |
| 13 | IN | `bUpdateAll` | `int` |
| 14 | IN | `sLoginId` | `varchar(100)` |
| 15 | IN | `sBrId` | `varchar(100)` |
| 16 | IN | `sSuId` | `varchar(100)` |
| 17 | OUT | `sCode` | `int` |
| 18 | OUT | `sReturn` | `varchar(4000)` |

## Body

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

## Narrative

**Business context:** 库存管理 / 成本核算 → 材料价格自动结转 — single-material variant of the materials weighted-average price calculator. On audit of a stock movement (生产领料/生产退料/采购入库/采购退货/材料调拨/材料报废/来料入库/材料盘点/材料库存调整/其他入库/分切单/送货单) the calling 审核 proc passes one material + warehouse + period; this proc recomputes that material's running weighted-average price from `viw_mitmaterialscheck`/`elematerials`, then propagates it back into the source document and the materials-stock check tables.

**What it does:** Resolves the material name via `viw_mitmaterialscheck` joined to `elematerials`. Reads system settings for `sPriceDecimal`/`sMoneyDecimal` and the chosen cost-mode (`p_iMaterialsCostMode`). For the requested `sMaterialsGuid`/`sMaterialsStyle`/`sDefineNo`/`sDefineNo2`/warehouse/location/period it sums入库金额+期初金额 and divides by qty (全月加权 / 移动加权 depending on cost-mode), then writes the resulting `dMaterialsPrice` back to the originating slave row identified by `sGuid` and refreshes downstream stock balances. `bUpdate`/`bFlag`/`bUpdateAll` flags select between first-pass distribution (分切单 master→slave) and the standard second-pass distribution.

**Invocation:** Called by every materials-side `Sp_Calc_s*` audit proc that needs to refresh the unit price after a stock movement — confirmed callers in DB: `Sp_Calc_sCut`, `Sp_Calc_sDgd`(+`_1226`/`_20250612`), `Sp_Calc_sDgdCL`, `Sp_Calc_sDYDgd`, `Sp_Calc_sMad`, `Sp_Calc_sMma`, `Sp_Calc_sMmm`(+`_copy1`), `Sp_Calc_sPmd_old`, `Sp_Calc_sPrj`, `Sp_Calc_sRgd`(+`1`/`_new`), `SP_Inventory_Materials_Inout_new`, `Sp_System_BatchPriceMoney`, plus the `_new` body. Reached transitively via `BusinessBaseServiceImpl.getPrcName` on those forms' 审核 button. Install: `script/标版/30100101/Sp_System_AutoMaterialsPriceSingle.sql`; archived copies under `script/标版/材料库存/` (`_Ret`, `_RetAll`) and `script/标版/30100101/Sp_System_AutoMaterialsPriceSingle_Old.sql`.
