﻿SELECT t0.FBILLNO,t0.FDATE,t0e.FID,t0e.FENTRYID,t0e.FMATERIALID
	,(CASE t0e_lk.FSTABLENAME 
		WHEN 'T_STK_MISDELIVERYENTRY' THEN t1.FPRICE --其他出库（退货）-成本价
		WHEN 'T_STK_INSTOCKENTRY' THEN t2.FPRICE --采购入库 -单价（不含税）
		WHEN 'T_STK_STKTRANSFERINENTRY1' THEN t3.FPRICE --分步式调入 -参考单价
		ELSE 0 
	END) AS newReferPrice
	,t0e.FReferPrice
	,t0e.FQTY
	,t0e.FReferAmount
	,t0e.FExplain
	,(CASE t0e_lk.FSTABLENAME 
		WHEN 'T_STK_MISDELIVERYENTRY' THEN '源_其他出库单:'+ t1.FBILLNO 
		WHEN 'T_STK_INSTOCKENTRY' THEN '源_采购入库单:'+ t2.FBILLNO 
		WHEN 'T_STK_STKTRANSFERINENTRY1' THEN '源_分步式调入单:'+ t3.FBILLNO
		ELSE ''
	END) AS 'newExplain'
	,t0e_lk.FSTABLENAME
	INTO #TMP_HAS_PARENT_MIS
FROM T_STK_MISDELIVERY t0
	INNER JOIN T_STK_MISDELIVERYENTRY t0e on t0.FID = t0e.FID
	INNER JOIN T_STK_MISDELIVERYENTRY_LK t0e_lk on t0e.FENTRYID = t0e_lk.FENTRYID
	OUTER APPLY (
		SELECT t1.FBILLNO,t1e.FPRICE
		FROM T_STK_MISDELIVERY t1 --其他出库单
			INNER JOIN T_STK_MISDELIVERYENTRY t1e on t1.FID = t1e.FID 
				AND (t1e.FID = t0e_lk.FSBILLID AND t1e.FENTRYID = t0e_lk.FSID AND t0e_lk.FSTABLENAME = 'T_STK_MISDELIVERYENTRY')
	) t1
	OUTER APPLY (
		SELECT t2.FBILLNO,t2e.FPRICE
		FROM T_STK_INSTOCK t2 --采购入库单
			INNER JOIN T_STK_INSTOCKENTRY_F t2e on t2.FID = t2e.FID
				AND (t2e.FID = t0e_lk.FSBILLID AND t2e.FENTRYID = t0e_lk.FSID AND t0e_lk.FSTABLENAME = 'T_STK_INSTOCKENTRY')
	) t2
	OUTER APPLY (
		SELECT t3.FBILLNO,(CASE LTRIM(RTRIM(t3e.FReferPrice)) WHEN '' THEN 0 ELSE CONVERT(decimal(23,6) ,t3e.FReferPrice) END) AS FPRICE
		FROM T_STK_STKTRANSFERIN t3 --分步式调入
			INNER JOIN T_STK_STKTRANSFERINENTRY t3e on t3.FID = t3e.FID
				AND (t3e.FID = t0e_lk.FSBILLID AND t3e.FENTRYID = t0e_lk.FSID AND t0e_lk.FSTABLENAME = 'T_STK_STKTRANSFERINENTRY1')
	) t3
WHERE 1 = 1 
	AND t0.FSTOCKORGID = 101542
	AND t0e_lk.FSTABLENAME IN ('T_STK_STKTRANSFERINENTRY1','T_STK_INSTOCKENTRY' ,'T_STK_MISDELIVERYENTRY')
	AND t0.FDATE >= '2023-11-01 00:00:00.000'

SELECT t1.* 
--UPDATE t0e SET t0e.FReferPrice = t1.newReferPrice
	--,t0e.FReferAmount = t1.newReferPrice * t0e.FQTY
	--, t0e.FExplain = t1.newExplain
FROM T_STK_MISDELIVERYENTRY t0e
	INNER JOIN #TMP_HAS_PARENT_MIS t1 on t0e.FENTRYID = t1.FENTRYID 
WHERE t1.newReferPrice != 0

DROP TABLE #TMP_HAS_PARENT_MIS