declare @FORG int,@leatTime int
set @FORG = 1
SET @leatTime = 30
SELECT t0.fid F_BGP_INVENTORYID
	,t0.FSTOCKID,t1.FMaterialId,t0.FLot
	,t0.FStockUnitId,t0.FBaseUnitId,t0.FQty,t0.FBaseQty
	,t0.FStockStatusId,t0.FStockLocId
	,DATEDIFF(DAY,t3.Maintdate,GETDATE()) - t2.F_BGP_DAY + 1 overday
	,DATEADD(DAY,(t2.F_BGP_DAY + 0.7),t3.Maintdate) as F_BGP_ShouldMainteDate
	,ISNULL(t3.FPRODUCEDATE,t0.FPRODUCEDATE) FPRODUCEDATE
	,ISNULL(t3.FEXPIRYDATE,t0.FEXPIRYDATE) FEXPIRYDATE
	,GETDATE() F_BGP_MAINTEPLANDATE,FOwnerTypeId,FOwnerId,FKeeperTypeId,FKeeperId,FStockStatusId,FAuxPropId,FSecQty,FSecUnitId,t3.Maintdate
FROM T_STK_INVENTORY t0
	INNER JOIN T_BD_MATERIAL t1 on t0.FMATERIALID = t1.FMASTERID AND t0.FSTOCKORGID = t1.FUSEORGID
	INNER JOIN T_BGP_MaintainType t2 on t1.F_BGP_MAINTAINCLASS = t2.FID AND t2.FNUMBER = '01'
	CROSS APPLY (
		SELECT ISNULL(t3.F_BGP_MaintDate,t3.FInStockDate) Maintdate,t3.FLOTID,t3.FPRODUCEDATE,t3.FEXPIRYDATE 
		FROM T_BD_LOTMASTER t3
		WHERE t3.FLOTID=t0.FLot
	) t3
WHERE 1 = 1
	AND DATEDIFF(DAY,t3.Maintdate ,GETDATE()) > t2.F_BGP_DAY - 30 AND t0.FSTOCKORGID = @FORG
	AND FBaseQty > 0 AND t1.FDOCUMENTSTATUS='C' AND FStockStatusId = 10000
	AND NOT EXISTS (
		SELECT 1 FROM T_BGP_MaintePlanB t4
		WHERE t4.F_BGP_BaseQty > t4.F_BGP_BaseMaintQty AND t4.F_BGP_INVENTORYID= t0.fid
	)
ORDER BY F_BGP_DosageForm,FSTOCKID,FMaterialId