CREATE TRIGGER [dbo].[TI_Exp_Resid] ON [dbo].[Exp_File]
FOR  INSERT
AS 
   DECLARE @TmpValue Money
   Update Dbo.Exp_Date
     Set Dbo.Exp_Date.K_Qty=Dbo.Exp_Date.K_Qty+
            (select sum(K_Qty)    
             FROM      Inserted I INNER JOIN
                      dbo.Havaleh H ON H.AutoId = I.AutoId
                      where  Exp_Date.A_Code=H.Reciver and Exp_Date.K_Code=H.K_Code And Exp_Date.Exp_date=I.Exp_Date)
     FROM     Inserted I INNER JOIN
                       Havaleh H ON H.AutoId = I.AutoId
     Where  i.AutoId=H.AutoId And Exp_Date.A_Code=H.Reciver and Exp_Date.K_Code=H.K_Code And Exp_Date.Exp_Date=I.Exp_Date And (Len(H.reciver)=3 )

   Insert Into Dbo.Exp_Date ( A_Code    , K_Code     ,  K_Qty , Exp_Date  )
      SELECT   H.Reciver , H.K_Code , Sum(I.K_Qty), I.Exp_Date
      FROM        Inserted I INNER JOIN
                        Havaleh  H ON  I.AutoId = H.AutoId 
      Where NOT EXISTS 
                (select E.A_Code , E.K_Code , E.K_Qty , E.Exp_Date from Dbo.Exp_Date E 
                 where E.A_Code = H.Reciver and E.K_Code = H.K_Code And E.Exp_Date = I.Exp_Date )  And (Len(H.Reciver)=3)
     Group By  H.Reciver , H.K_Code , I.Exp_Date

     SELECT @TmpValue = (select sum(I.K_Qty) FROM Inserted I  INNER JOIN dbo.Havaleh  H ON H.AutoId = i.AutoId
                         INNER JOIN dbo.Exp_Date ON Exp_Date.A_Code=H.Sender and Exp_Date.K_Code=H.K_Code And Exp_Date.Exp_date=I.Exp_Date
                         where  Exp_Date.A_Code=H.Sender and Exp_Date.K_Code=H.K_Code And Exp_Date.Exp_date=I.Exp_Date And (Len(H.Sender) =3)
				    	 )

    UPDATE Dbo.Exp_Date
    Set Dbo.Exp_Date.K_Qty= 
	CASE 
	  WHEN Exp_Date.K_Qty >= @TmpValue  THEN Exp_Date.K_Qty - @TmpValue
	  ELSE 0
	End
     FROM     Inserted I INNER JOIN
                       Havaleh H ON H.AutoId = I.AutoId
     Where  i.AutoId=H.AutoId And Exp_Date.A_Code=H.sender and Exp_Date.K_Code=H.K_Code And Exp_Date.Exp_Date=I.Exp_Date And (Len(H.sender)=3 )
      
