CREATE  TRIGGER [dbo].[TI_Over_Under_Factor] ON [dbo].[Over_Under_Factor]
FOR INSERT
AS 
Declare    @Id_Havaleh          BigInt
Declare    @Auto_Id_Havaleh     BigInt
Declare    @msg                 Bigint
Declare    @Act                 Smallint 
Declare    @Guy_Code            VarChar(20)
Declare    @Price               Money
Declare    @Id_Over_Under       bigint
Declare    @KindFlag            Char(1)
Declare    @Note                NVarchar(30)
Declare    @NuKharid            Varchar(8)
Declare    @NuForosh            Varchar(8)
Declare    @Nu_Bargasht_Forosh  Varchar(8)
Declare    @Nu_Bargasht_Kharid  Varchar(8)

  Select @Id_Havaleh = Id_Havaleh,  @Auto_Id_Havaleh= Auto_Id_Havaleh From Inserted
  Select @KindFlag = Kind_Flag , @NuKharid= Nu_Kharid, 
         @NuForosh = Nu_Forosh , @Nu_Bargasht_Kharid = Nu_Bargasht_Kharid,
         @Nu_Bargasht_Forosh = Nu_Bargasht_Forosh From HeadH Where Id_Havaleh = @Id_Havaleh 
  IF @KindFlag = '3'
    Set @Note = @NuKharid
  Else
    IF @KindFlag = '4'
      Set @Note = @Nu_Bargasht_Kharid
  Else
    IF @KindFlag in('5', '7','9')
      Set @Note = @NuForosh
  Else
    IF @KindFlag in ('6','8','0') 
      Set @Note = @Nu_Bargasht_Forosh


  Set @Note = Cast(@Id_Havaleh as Varchar(10)) + ' فاكتور ' + @Note
  
-- تعريف يک فچ روي اطلاعات اينسرت شده در فايل اور اندر فاکتور
  Declare OvUn_Cursor Cursor LOCAL FOR
   SELECT     Guy_Code,SUM(Round(Price,0)) , Act_Code, Id_Havaleh,AutoId
   FROM         Inserted
   GROUP BY Act_Code, Guy_Code,Id_Havaleh,AutoId

               
  OPEN OvUn_Cursor
  
  FETCH NEXT FROM OvUn_Cursor INTO @Guy_Code,@Price,@Act,@Id_Havaleh,@Id_Over_Under
 
   WHILE @@FETCH_STATUS = 0     
   BEGIN 
     IF @Auto_Id_Havaleh = 0 
       Set @Id_Havaleh = 0 
     Exec  @Msg= Create_Sanad_Auto @Msg  , @Act   ,  @Guy_Code   ,@Price    ,@Id_Havaleh , @Note  ,@Id_Over_Under
     If @Msg > 0 
       Print ' Sodor shod'
     Else 
       Print @Msg
    
     FETCH NEXT FROM OvUn_Cursor INTO @Guy_Code,@Price,@Act,@Id_Havaleh,@Id_Over_Under
   End

  CLOSE OvUn_Cursor
  DEALLOCATE OvUn_Cursor

