UPDATE VS4TPODelivery set TPDETotalDelivery2=(SELECT Sum(TInMInQuantity2) from VS4VInventoryMB WHERE TInMTPODNo=TPDETPOBTPODNo AND TInMTPOBLn=TPDETPOBLn AND TInMTPDELn=TPDELn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TPODelivery set TPDETotalDelivery2=0 where TPDETotalDelivery2 is null
UPDATE VS4TPODelivery set TPDETotalArrear2=TPDEQuantity2-TPDETotalDelivery2
UPDATE VS4TPODelivery set TPDETotalArrear2=0 where TPDETotalArrear2 is null

UPDATE VS4TPOMB set TPOBTotalDelivery2=(SELECT Sum(TPDETotalDelivery2) from VS4TPODelivery WHERE TPOBTPODNo=TPDETPOBTPODNo AND TPOBLn=TPDETPOBLn)
UPDATE VS4TPOMB set TPOBTotalDelivery2=0 where TPOBTotalDelivery2 is null

UPDATE VS4TPODelivery set TPDETotalDelivery3=(SELECT Sum(TInMInQuantity3) from VS4VInventoryMB WHERE TInMTPODNo=TPDETPOBTPODNo AND TInMTPOBLn=TPDETPOBLn AND TInMTPDELn=TPDELn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TPODelivery set TPDETotalDelivery3=0 where TPDETotalDelivery3 is null
UPDATE VS4TPODelivery set TPDETotalArrear3=TPDEQuantity3-TPDETotalDelivery3
UPDATE VS4TPODelivery set TPDETotalArrear3=0 where TPDETotalArrear3 is null

UPDATE VS4TPOMB set TPOBTotalDelivery3=(SELECT Sum(TPDETotalDelivery3) from VS4TPODelivery WHERE TPOBTPODNo=TPDETPOBTPODNo AND TPOBLn=TPDETPOBLn)
UPDATE VS4TPOMB set TPOBTotalDelivery3=0 where TPOBTotalDelivery3 is null


UPDATE VS4TPODelivery set TPDETotalDelivery=(SELECT Sum(TInMInQuantity) from VS4VInventoryMB WHERE TInMTPODNo=TPDETPOBTPODNo AND TInMTPOBLn=TPDETPOBLn AND TInMTPDELn=TPDELn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TPODelivery set TPDETotalDelivery=0 where TPDETotalDelivery is null
UPDATE VS4TPODelivery set TPDETotalArrear=TPDEQuantity-TPDETotalDelivery
UPDATE VS4TPODelivery set TPDETotalArrear=0 where TPDETotalArrear is null

UPDATE VS4TPOMB Set TPOBFlag2=(SELECT TPDURatio FROM VS4TProductUnit WHERE TPDUTPdtCode=TPOBTPdtCode AND TPDUTUntCode=TPOBTUntCode)
UPDATE VS4TPOMB Set TPOBFlag2=1 where TPOBFlag2 = 0 or TPOBFlag2 is null
UPDATE VS4TPOMB set TPOBTotalDelivery=(SELECT Sum(TPDETotalDelivery) from VS4TPODelivery WHERE TPOBTPODNo=TPDETPOBTPODNo AND TPOBLn=TPDETPOBLn)
UPDATE VS4TPOMB set TPOBTotalDelivery=0 where TPOBTotalDelivery is null
UPDATE VS4TPOMB set TPOBTotalDelivery=TPOBTotalDelivery/TPOBFlag2

Update VS4TPO SET TPODFlag3=0,TPODDeliveryStatus=0 
Update VS4TPO SET TPODFlag3=0,TPODDeliveryStatus=1 WHERE 
(SELECT Sum(TPDETotalDelivery)AS C FROM VS4VPODelivery WHERE TPODApproveStatus=1 AND TPOBStatus=1 AND TPDETPOBTPODNo=VS4TPO.TPODNo) > 0
Update VS4TPO SET TPODFlag3=0,TPODDeliveryStatus=2 WHERE 
(SELECT Sum(TPDETotalArrear)AS C FROM VS4VPODelivery WHERE TPODApproveStatus=1 AND TPOBStatus=1 AND TPDETPOBTPODNo=VS4TPO.TPODNo) <= 0

