CREATE TRIGGER [dbo].[TolidAuto] ON [dbo].[TmpHavaleh]
For Insert
AS 
 Declare @Make_Anbar        Varchar(5)
 Set     @Make_Anbar        ='09999'
 Declare @msg_num           Numeric(18,0)
 Declare @Last_AutoId       BigInt
 Declare @TmpIdHavaleh      Numeric(18,0)
 Declare @TmpK_Code         varchar(15)
 Declare @TmpQty            Real
 Declare @Link_Record       Real
 Declare @Auto_Id           Bigint

----------------------------------------------------------------------------------------------------------------
--تعريف متغيرهاي فچ 

 Declare @F_Sender           Varchar(5)
 Declare @F_K_Code           Varchar(15)
 Declare @F_ACC              Real
 Declare @F_EditQty_Flag     Flag
 Declare @F_Make_Flag        Flag
 Declare @KindFactor         Char(1)
 Declare @KindSave           Char(1)

-- اگر رکوردي که به تمپ حواله اضافه شد فلاگ کالاي ساختني آن يک بود
Select @KindFactor = TmpH.Kind_Flag , @KindSave =  TmpH.Kind_Save From TmpHeadH  TmpH Inner Join Inserted I On(TmpH.Id_Havaleh = I.Id_Havaleh)
Where TmpH.Id_Havaleh = I.Id_Havaleh
Group By  TmpH.Kind_Flag, TmpH.Kind_Save
IF @KindFactor = '7'
Begin
   IF ((Select Make_Flag From inserted) = 1) and ((Select Len(Sender) From inserted) = 5 or (Select Len(Reciver) From inserted) = 5)
   Begin
      Select @TmpIdHavaleh=Id_Havaleh , @TmpK_Code=K_Code , @TmpQty=K_Qty1 , 
                @Link_Record=Link_Record , @Auto_Id=AutoId  From Inserted

      DECLARE MakeD_Kala  CURSOR  LOCAL FOR
      SELECT    dbo.Make_Kala.Sender, dbo.Make_Kala.K_Code_M, dbo.Make_Kala.Account_unit1,dbo.Make_Kala.EditQty_Flag, dbo.KalaId.Make_Flag
      FROM       dbo.Make_Kala INNER JOIN dbo.KalaId ON dbo.Make_Kala.K_Code_M = dbo.KalaId.K_Code
      WHERE     dbo.Make_Kala.K_Code = @TmpK_Code

      OPEN MakeD_Kala
  
      FETCH NEXT FROM MakeD_Kala  INTO @F_Sender , @F_K_Code , @F_ACC , @F_EditQty_Flag, @F_Make_Flag

      WHILE @@FETCH_STATUS = 0     
       BEGIN 
           IF @F_EditQty_Flag=1  Set @F_ACC= @TmpQty*@F_ACC

           Exec   Add_One_Kala   @msg_num,@Last_AutoId,@TmpIdHavaleh ,    @F_Sender   ,   @Make_Anbar ,  @F_K_Code  ,   @F_ACC  ,  1,   @Auto_Id  , @KindSave
           FETCH NEXT FROM MakeD_Kala INTO @F_Sender , @F_K_Code , @F_ACC , @F_EditQty_Flag,@F_Make_Flag
       End
       CLOSE MakeD_Kala
       DEALLOCATE MakeD_Kala
   End
End
