CREATE TRIGGER [dbo].[Td_History_Detail_Factors] ON [dbo].[Havaleh] 
FOR DELETE 
AS
  Declare @Id_Havaleh Numeric(18,0)
  Declare @AutoId Numeric(18,0)
  Declare @Sender varchar(5)
  Declare @Reciver varchar(7)
  Declare @Radif smallint
  Declare @K_Code varchar (15) 
  Declare @K_Qty1 money
  Declare @K_Qty2 real
  Declare @R_Unit1_2 real
  Declare @Price_KHarid money
  Declare @Price_Omdeh money
  Declare @Price_Forosh money
  Declare @Exp_Flag  Bit
  Declare @Point_Flag Bit
  Declare @Serial_Flag Bit
  Declare @Make_Flag Bit
  Declare @Hamrah_Flag Bit
  Declare @EditQty_Flag Bit
  Declare @CtrMojodi char (1) 
  Declare @Note nvarchar (60) 
  Declare @KindFlag char(1)
  DECLARE @DeletedUser Smallint


  SET @DeletedUser = Manager.dbo.SessionUser(@@Spid,0)
  DECLARE Cursor_DeleteDetailFactor Cursor Local For 
  Select Deleted.Id_Havaleh,Deleted.AutoId,Deleted.Sender,Deleted.Reciver,
         Deleted.Radif,Deleted.K_Code,Deleted.K_Qty1,Deleted.K_Qty2,Deleted.R_Unit1_2,
         Deleted.Price_Kharid,Deleted.Price_Forosh,Deleted.Point_Flag,Deleted.Serial_Flag,
         Deleted.Hamrah_Flag,Deleted.CtrMojodi,Deleted.Exp_Flag,Deleted.Make_Flag,Deleted.Note, 
         HeadH.Kind_Flag From Deleted Inner Join HeadH 
         On (Deleted.Id_Havaleh = HeadH.Id_Havaleh)

  Open Cursor_DeleteDetailFactor
  Fetch Next From Cursor_DeleteDetailFactor Into @Id_Havaleh,@AutoId,@Sender,@Reciver,@Radif,@K_Code,@K_Qty1,
                                             @K_Qty2,@R_Unit1_2,@Price_Kharid,@Price_Forosh,@Point_Flag,
                                             @Serial_Flag,@Hamrah_Flag,@CtrMojodi,@Exp_Flag,@Make_Flag,@Note,@KindFlag

  Begin Tran Delete_Rec

  While @@FETCH_STATUS = 0     
  Begin
    Insert Into History_Detail_Factors (Id_Havaleh,AutoId,Sender,Reciver,Radif,K_Code,K_Qty1,
                                      K_Qty2,R_Unit1_2,Price_Kharid,Price_Forosh,Point_Flag,
                                      Serial_Flag,Hamrah_Flag,CtrMojodi,Exp_Flag,Make_Flag,Note,Status, UserIdForSelete)
                              Values (@Id_Havaleh,@AutoId,@Sender,@Reciver,@Radif,@K_Code,@K_Qty1,
                                      @K_Qty2,@R_Unit1_2,@Price_Kharid,@Price_Forosh,@Point_Flag,
                                      @Serial_Flag,@Hamrah_Flag,@CtrMojodi,@Exp_Flag,@Make_Flag,@Note,@KindFlag, @DeletedUser)
    If @@Error > 0 
      RollBack Tran Delete_Rec

    Fetch Next From Cursor_DeleteDetailFactor  Into @Id_Havaleh,@AutoId,@Sender,@Reciver,@Radif,@K_Code,@K_Qty1,
                                                @K_Qty2,@R_Unit1_2,@Price_Kharid,@Price_Forosh,@Point_Flag,
                                                @Serial_Flag,@Hamrah_Flag,@CtrMojodi,@Exp_Flag,@Make_Flag,@Note,@KindFlag
  End --While @@FETCH_STATUS = 0  

  Commit Tran Delete_Rec
  CLOSE  Cursor_DeleteDetailFactor
  DEALLOCATE  Cursor_DeleteDetailFactor

