CREATE TRIGGER [dbo].[TUH_Mojodi_Anbar] ON [dbo].[Havaleh]
FOR  Update
AS 
Declare @Sender varchar(8)
Declare @Reciver varchar(8)
Declare @KQtyIns money
Declare @KQtyDel Money
Declare @KCode varchar(20)
Declare @IdHavaleh Bigint
Declare @Tot_kharid Money
Declare @Tot_Forosh Money
Declare @Tot_Omdeh MONEY
DECLARE @JetId Int


IF Update(K_Qty1) Or UPDATE(Price_Kharid) Or UPDATE(Price_Forosh) Or UPDATE(Price_Omdeh)
Begin
 Declare Cursor_Insert Cursor For
 Select  Inserted.Sender, Inserted.Reciver, Inserted.K_Code, Inserted.K_Qty1, Deleted.K_Qty1, Deleted.JetId  From Inserted
  Inner Join Deleted On Inserted.K_Code = Deleted.K_Code And Inserted.Sender = Deleted.Sender
  Open Cursor_Insert
  Fetch Next From  Cursor_Insert into @Sender, @Reciver, @KCode, @KQtyIns, @KQtyDel ,@JetId
  While @@Fetch_Status = 0 
  Begin
      IF Len(@Sender) = 3
	  begin
          Update Anbar Set Mojodi = Mojodi - (@KQtyIns - @KQtyDel) , Exit_Fa = Exit_Fa +  (@KQtyIns - @KQtyDel) Where K_Code = @KCode And  A_Code  = @Sender
    	IF @JetId IS NOT NULL
		   UPDATE dbo.JetPrint SET SaleQty = SaleQty + (@KQtyIns - @KQtyDel) WHERE Id= @JetId	
      end
      IF Len(@Reciver) = 3
          Update Anbar Set Mojodi = Mojodi +   (@KQtyIns - @KQtyDel) , Resive_Fa = Resive_Fa +  (@KQtyIns - @KQtyDel) Where K_Code = @KCode And  A_Code  = @Reciver
     Fetch Next From  Cursor_Insert into @Sender, @Reciver, @KCode, @KQtyIns, @KQtyDel ,@JetId
  End
  Close Cursor_Insert
  Deallocate Cursor_Insert
End
