UPDATE VS4TSODelivery set TMDSTotalDelivery2=(SELECT Sum(TInMOutQuantity2) from VS4VInventoryMB WHERE TInMTSODNo=TMDSTSOBTSODNo AND TInMTSOBLn=TMDSTSOBLn AND TInMTMDSLn=TMDSLn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TSODelivery set TMDSTotalDelivery2=0 where TMDSTotalDelivery2 is null
UPDATE VS4TSODelivery set TMDSTotalArrear2=TMDSQuantity2-TMDSTotalDelivery2
UPDATE VS4TSODelivery set TMDSTotalArrear2=0 where TMDSTotalArrear2 is null

UPDATE VS4TSOMB set TSOBTotalDelivery2=(SELECT Sum(TMDSTotalDelivery2) from VS4TSODelivery WHERE TSOBTSODNo=TMDSTSOBTSODNo AND TSOBLn=TMDSTSOBLn)
UPDATE VS4TSOMB set TSOBTotalDelivery2=0 where TSOBTotalDelivery2 is null

UPDATE VS4TSODelivery set TMDSTotalDelivery3=(SELECT Sum(TInMOutQuantity3) from VS4VInventoryMB WHERE TInMTSODNo=TMDSTSOBTSODNo AND TInMTSOBLn=TMDSTSOBLn AND TInMTMDSLn=TMDSLn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TSODelivery set TMDSTotalDelivery3=0 where TMDSTotalDelivery3 is null
UPDATE VS4TSODelivery set TMDSTotalArrear3=TMDSQuantity3-TMDSTotalDelivery3
UPDATE VS4TSODelivery set TMDSTotalArrear3=0 where TMDSTotalArrear3 is null

UPDATE VS4TSOMB set TSOBTotalDelivery3=(SELECT Sum(TMDSTotalDelivery3) from VS4TSODelivery WHERE TSOBTSODNo=TMDSTSOBTSODNo AND TSOBLn=TMDSTSOBLn)
UPDATE VS4TSOMB set TSOBTotalDelivery3=0 where TSOBTotalDelivery3 is null


UPDATE VS4TSODelivery set TMDSTotalDelivery=(SELECT Sum(TInMOutQuantity) from VS4VInventoryMB WHERE TInMTSODNo=TMDSTSOBTSODNo AND TInMTSOBLn=TMDSTSOBLn AND TInMTMDSLn=TMDSLn AND TInMStatus=1 AND TInvApproveStatus=1 AND TInvCancelStatus=0)
UPDATE VS4TSODelivery set TMDSTotalDelivery=0 where TMDSTotalDelivery is null
UPDATE VS4TSODelivery set TMDSTotalArrear=TMDSQuantity-TMDSTotalDelivery
UPDATE VS4TSODelivery set TMDSTotalArrear=0 where TMDSTotalArrear is null

UPDATE Vs4TSOMB Set TSOBFlag2=(SELECT TPDURatio FROM VS4TProductUnit WHERE TPDUTPdtCode=TSOBTPOSCode AND TPDUTUntCode=TSOBTUntCode)
UPDATE Vs4TSOMB Set TSOBFlag2=1 where TSOBFlag2 = 0 or TSOBFlag2 is null
UPDATE VS4TSOMB set TSOBTotalDelivery=(SELECT Sum(TMDSTotalDelivery) from VS4TSODelivery WHERE TSOBTSODNo=TMDSTSOBTSODNo AND TSOBLn=TMDSTSOBLn)
UPDATE VS4TSOMB set TSOBTotalDelivery=0 where TSOBTotalDelivery is null
UPDATE VS4TSOMB set TSOBTotalDelivery=TSOBTotalDelivery/TSOBFlag2

Update VS4TSO SET TSODFlag3=0,TSODDeliveryStatus=0 
Update VS4TSO SET TSODFlag3=0,TSODDeliveryStatus=1 WHERE 
(SELECT Sum(TMDSTotalDelivery)AS C FROM VS4VSODelivery WHERE TSODApproveStatus=1 AND TSOBStatus=1 AND TMDSTSOBTSODNo=VS4TSO.TSODNo) > 0
Update VS4TSO SET TSODFlag3=0,TSODDeliveryStatus=2 WHERE 
(SELECT Sum(TMDSTotalArrear)AS C FROM VS4VSODelivery WHERE TSODApproveStatus=1 AND TSOBStatus=1 AND TMDSTSOBTSODNo=VS4TSO.TSODNo) <= 0

