declare @FORG int,@leatTime int
set @FORG = 1
SET @leatTime = 30
SELECT t0.fid F_BGP_INVENTORYID
	,t0.FSTOCKID
	,t1.FMaterialId
	,FLot
	,FStockUnitId, FBaseUnitId, FQty,FBaseQty, FStockStatusId
	,FStockLocId ,DATEDIFF(DAY,Maintdate ,GETDATE())-89 overday
	,dateadd(DAY,90.7,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
	,Maintdate 
FROM T_STK_INVENTORY t0
	,T_BD_MATERIAL t1
	,T_BGP_MaintainType t2
	,(SELECT ISNULL(F_BGP_MaintDate,FInStockDate) Maintdate
		,FLOTID,FPRODUCEDATE,FEXPIRYDATE 
	FROM T_BD_LOTMASTER) t3 
WHERE t0.FMaterialId = t1.FMasterId    
	AND F_BGP_MaintainClass=t2.FID 
	AND t2.F_BGP_DAY = 90 
	AND t3.FLOTID=t0.FLot 
	AND DATEDIFF(DAY,Maintdate ,GETDATE()) > 90 - @leatTime
	AND t0.FSTOCKORGID = @FORG
	AND FBaseQty > 0
	AND t1.FDOCUMENTSTATUS='C' 
	AND FStockStatusId = 10000 
	AND t1.FuseORGID=@FORG
	AND NOT EXISTS(
		SELECT F_BGP_INVENTORYID 
		FROM T_BGP_MaintePlanB mb 
		WHERE F_BGP_BaseQty > F_BGP_BaseMaintQty AND F_BGP_INVENTORYID= t0.fid
	)    
ORDER BY F_BGP_DosageForm,FSTOCKID,FMaterialId