declare @FORG int
set @FORG = 1
SELECT i.fid F_BGP_INVENTORYID, i.FSTOCKID, m.FMaterialId, FLot
,FStockUnitId, FBaseUnitId, FQty,FBaseQty, FStockStatusId
,FStockLocId ,DATEDIFF(day,Maintdate ,getdate())-89 overday
,dateadd(day,90.7,Maintdate) as F_BGP_ShouldMainteDate
,isnull(l.FPRODUCEDATE,i.FPRODUCEDATE)FPRODUCEDATE
,isnull(l.FEXPIRYDATE,i.FEXPIRYDATE)FEXPIRYDATE
,getdate() F_BGP_MAINTEPLANDATE,FOwnerTypeId
,FOwnerId,FKeeperTypeId,FKeeperId,FStockStatusId
,FAuxPropId,FSecQty,FSecUnitId,Maintdate 
FROM T_STK_INVENTORY i
	,T_BD_MATERIAL m
	,T_BGP_MaintainType mt
	,(SELECT isnull(F_BGP_MaintDate,FInStockDate) Maintdate
		,FLOTID,FPRODUCEDATE,FEXPIRYDATE 
	FROM T_BD_LOTMASTER) 
l WHERE i.FMaterialId = m.FMasterId    
	AND F_BGP_MaintainClass=mt.FID 
	AND F_BGP_DAY = 90 
	AND l.FLOTID=i.FLot 
	AND DATEDIFF(day,Maintdate ,getdate()) > 90 - 90
	AND i.FSTOCKORGID = @FORG
	AND FBaseQty > 0
	AND m.FDOCUMENTSTATUS='C' 
	AND FStockStatusId = 10000 
	AND m.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= i.fid )    
ORDER BY F_BGP_DosageForm,FSTOCKID,FMaterialId