
Create TRIGGER [dbo].[Td_History_Delete_HeadGh] ON [dbo].[HeadGh] 
FOR DELETE 
AS

Declare @Id_Havaleh bigint
Declare @Id_Sanad bigint
Declare @Id_Ghest bigint
Declare @Id_Manual varchar (10) 
Declare @Kind_Flag char (1) 
Declare @TarikhBargeh SmallDateTime
Declare @T_Bedeh money
Declare @T_Bestan money
Declare @Guy_Code varchar (5) 
Declare @Tarikh SmallDateTime
Declare @User_Id Smallint
Declare @Act int
Declare @note nvarchar (90) 
Declare @New_status char (1) 
Declare @Old_Status char (1) 

 Declare Delete_Cursor_HeadGh  Cursor Local For
 Select  Id_Havaleh, Id_Sanad, Id_Ghest, Id_Manual, Kind_Flag, TarikhBargeh, T_Bedeh, T_Bestan,
             Guy_Code, Tarikh, User_Id, Act, note, New_Status, Old_Status  From Deleted   

 Open Delete_Cursor_HeadGh
 Fetch Next From Delete_Cursor_HeadGh Into  @Id_Havaleh, @Id_Sanad, @Id_Ghest, @Id_Manual, @Kind_Flag, @TarikhBargeh, @T_Bedeh, @T_Bestan,
             @Guy_Code, @Tarikh, @User_Id, @Act, @note, @New_Status, @Old_Status
 Begin Tran DeleteRecHeadGh
 While @@Fetch_Status = 0 
 Begin
      Insert Into History_Delete_HeadGh ( Id_Havaleh, Id_Sanad, Id_Ghest, Id_Manual, Kind_Flag, TarikhBargeh, T_Bedeh, T_Bestan,
				                Guy_Code, Tarikh, User_Id, Act, note, New_Status, Old_Status,UserIdForDelete)
  		                            Values (@Id_Havaleh, @Id_Sanad, @Id_Ghest, @Id_Manual, @Kind_Flag, @TarikhBargeh, @T_Bedeh, @T_Bestan,
				               @Guy_Code, @Tarikh, @User_Id, @Act, @note, @New_Status, @Old_Status,@User_Id)

     IF @@Error > 0 
        RollBack Tran DeleteRecHeadGh
    
    
    Fetch Next From Delete_Cursor_HeadGh Into  @Id_Havaleh, @Id_Sanad, @Id_Ghest, @Id_Manual, @Kind_Flag, @TarikhBargeh, @T_Bedeh, @T_Bestan,
               @Guy_Code, @Tarikh, @User_Id, @Act, @note,  @New_Status, @Old_Status
 End
 
 Commit Tran DeleteRecHeadGh
 Close           Delete_Cursor_HeadGh
 Deallocate  Delete_Cursor_HeadGh



