CREATE TRIGGER [dbo].[TD_HistoryDeleteSanad] ON [dbo].[Sanad] 
After DELETE 
AS

 Declare @Guid_Sanad    uniqueidentifier 
 Declare @Id_Sanad      numeric(19)
 Declare @Type          char (1)  
 Declare @Comment       nvarchar(50)
 Declare @Acc_Code      varchar(20)
 Declare @NOTE          nvarchar(120)
 Declare @RADIF         smallint
 Declare @BEDEH         money
 Declare @BESTAN        money
 Declare @Auto_Create   Flag
 Declare @User_ID       UserId
 Declare @Tarikh        SysTarikh
 Declare @Nu_Vajeh      bigint
 Declare @Nu_Havaleh    bigint
 Declare @Nu_Over_Under bigint
 Declare @Nu_Ghest      bigint
 Declare @FlagFactor    char(1)  
 Declare @FlagVajh      smallint
 Declare @NumberSanad   Float
 Declare @DeletedUser   SMALLINT
 
 SET @DeletedUser = Manager.dbo.SessionUser(@@sPid,0)
 Declare Delete_Cursor  Cursor Local For
 Select  Guid_Sanad, Id_Sanad,Type, Comment, Acc_Code,NOTE , 
         RADIF, BEDEH , BESTAN, Auto_Create , User_ID, 
         Tarikh, Nu_Vajeh,Nu_Havaleh,Nu_Over_Under,Nu_Ghest, FlagFactor,FlagVajh From Deleted   
 Open Delete_Cursor
 Fetch Next From Delete_Cursor Into @Guid_Sanad, @Id_Sanad,@Type, @Comment, @Acc_Code,@NOTE , 
                                    @RADIF, @BEDEH , @BESTAN, @Auto_Create , @User_ID, 
                                    @Tarikh, @Nu_Vajeh,@Nu_Havaleh,@Nu_Over_Under,@Nu_Ghest, @FlagFactor,@FlagVajh
 Select @NumberSanad = Nu_Manual From HeadS Where Id_Sanad = @Id_Sanad 
 Begin Tran DeleteRec
 While @@Fetch_Status = 0 
 Begin
   Insert Into History_Delete_Sanad (Guid_Sanad, NumberSanad, Id_Sanad,Type, Comment, Acc_Code,NOTE , 
                                     RADIF, BEDEH , BESTAN, Auto_Create , User_ID, 
                                     Tarikh, Nu_Vajeh,Nu_Havaleh,Nu_Over_Under,Nu_Ghest, FlagFactor,FlagVajh , UserIdForDSelete)
                             Values (@Guid_Sanad, @NumberSanad, @Id_Sanad,@Type, @Comment, @Acc_Code,@NOTE , 
                                     @RADIF, @BEDEH , @BESTAN, @Auto_Create , @User_ID, 
                                     @Tarikh, @Nu_Vajeh,@Nu_Havaleh,@Nu_Over_Under,@Nu_Ghest, @FlagFactor,@FlagVajh , @DeletedUser)
   If @@Error > 0 
     RollBack Tran DeleteRec
 
   Fetch Next From Delete_Cursor Into @Guid_Sanad, @Id_Sanad,@Type, @Comment, @Acc_Code,@NOTE , 
                                      @RADIF, @BEDEH , @BESTAN, @Auto_Create , @User_ID, 
                                      @Tarikh, @Nu_Vajeh,@Nu_Havaleh,@Nu_Over_Under,@Nu_Ghest, @FlagFactor,@FlagVajh
 End
 
 Commit Tran DeleteRec
 Close       Delete_Cursor
 Deallocate  Delete_Cursor