# `Sp_System_MaterialsCost` (procedure) > @author:杨恒林 @date:20210521 封存 @describe:全月加权计算价格后 期初金额 + 采购入库金额+期它入库金额/ 期初数量 + 采购入库金额+期它入库金额 更新到其它各单据 bUpdate = 0:第一次分摊,分切单主表分摊到从表。 第二次正常分摊 - **Type:** PROCEDURE - **Deterministic:** NO - **SQL data access:** CONTAINS SQL ## Parameters | # | Mode | Name | Type | |---|---|---|---| | 1 | IN | `sProInParam` | `varchar(10000)` | | 2 | IN | `iSecond` | `int` | | 3 | IN | `sMakePerson` | `varchar(100)` | | 4 | IN | `sBrId` | `varchar(100)` | | 5 | IN | `sSuId` | `varchar(100)` | | 6 | OUT | `sReturn` | `varchar(4000)` | | 7 | OUT | `sCode` | `int` | ## Body _Body is not pre-cached. To inspect: `mysql --defaults-file=~/.my.cnf -e 'SHOW CREATE PROCEDURE `Sp_System_MaterialsCost`'`._ ## Narrative **Business context:** 成本核算 / 全月加权材料价格计算 — per the procedure `COMMENT` (杨恒林, 2021-05-21): full-month weighted-average price = (期初金额 + 采购入库金额 + 其它入库金额) / (期初数量 + 采购入库数量 + 其它入库数量). Computes the period's material weighted price, writes it into the materials-cost ledger, and pushes the price back into each consuming bill so downstream calculations (产品成本, 工单成本) work off a single canonical 材料价 per period. `iSecond` flag controls first-pass (master-to-slave price seed) vs subsequent reallocation. **What it does:** Validates the `sProInParam` JSON of selected `sysaccountperiod` ids. For each period: reads `sPeriodId`, gathers prior-period balance via `Sp_MaterialsCarryforward`, builds the weighted price across `mitmaterialspurchaseinslave` (采购入库), and other inbound flows, then upserts `accmaterialsstore` (materials cost ledger) and `Sp_EleMaterialsStock` temp; deletes and rebuilds `mitmaterialsstoreadjustmoneymaster`/`slave` (adjustment journals) when prices change; loops through 分切单 (`mitmaterialscutmaster`) to re-spread cost; calls `SP_Sis_GetMaxNo` for adjustment bill numbers; finally updates `sysaccountperiod` flags. **Invocation:** Called from `Sp_System_ProductionCost`, `Sp_System_ProductionCost_new`, and `Sp_System_ProductionCost24222` (production-cost runs need materials priced first). No direct UI binding; reached transitively when the user clicks 生产成本计算 on the 月度成本 grid. Install script `script/标版/30100101/cost/Sp_System_MaterialsCost.sql`. Body is 65K chars — most of the bulk is the multi-stage temp-table assembly for the weighted-price spread.