Create  TRIGGER [dbo].[TI_Over_Under_Cash]	 ON [dbo].[Over_Under_Factor_Drug]
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    @NuForosh            Varchar(8)
Declare    @Nu_Bargasht_Forosh  Varchar(8)

  Select @Id_Havaleh = Id_Havaleh From Inserted
  Select @NuForosh = Nu_Forosh , @Nu_Bargasht_Forosh = Nu_Bargasht_Forosh, 
  @KindFlag = Kind_Flag
  From DrugH Where Id_Havaleh = @Id_Havaleh
  
  
  IF @KindFlag = '1'
    Set @Note = @NuForosh
  Else
    IF @KindFlag = '2'
      Set @Note = @Nu_Bargasht_Forosh

  Set @Note = ' بابت نسخه ' + @Note
  
-- تعريف يک فچ روي اطلاعات اينسرت شده در فايل اور اندر فاکتور
  Declare OvUn_Cursor Cursor FOR
  SELECT '10000',SUM(Round(Price,0)) , Act_Code, Id_Havaleh,AutoId
  FROM Inserted 
  Where Act_Code > 0 
  GROUP BY Act_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
