--msg-num = -2 موردي براي صدور وجود ندارد
--msg-num = -5 خطاي سيستم

Create     PROCEDURE [dbo].[Sodor_Sanad]   @msg_num Bigint OUTPUT,@TmpId BigInt
 AS
 set @msg_num=0
If (Select Count(*)  From Dbo.TmpHeadS Where Id_Sanad = @TmpId  ) > 0   And  (Select Count(*)  From Dbo.TmpSanad  Where Id_Sanad = @TmpId) > 0
 Begin
   Begin Tran T1 
   Declare @Last_Id               BigInt
   Declare @Id_Cheqe              BigInt 

      Insert Into Dbo.HeadS( Nu_Manual , Balance , Note , Fiexd , [Auto] , [User_Id] ,Tarikh_user, Store_Code )
                     Select            Nu_Manual , Balance , Note , Fiexd , [Auto] , [User_Id] ,Tarikh_user,Store_Code
                    From Dbo.TmpHeadS
                    Where Id_Sanad=@TmpId	

     If @@Error > 0  
     Begin
       ROLLBACK TRANSACTION T1
       RETURN @msg_num 
     end
      

      Select @Last_Id=Scope_Identity()
 
      -- رکوردهاي جدول تمپ را به جدول اصلي حواله اضافه ميکند
      Insert Into Dbo.Sanad(Id_Sanad , Type,Comment,Acc_Code,Note,Radif,Bedeh,Bestan,Edit_Flag,Auto_Create,[User_Id],Tarikh,Guid_Sanad)
           Select                    @Last_Id , Type,Comment,Acc_Code,Note,Radif,Bedeh,Bestan,Edit_Flag,Auto_Create,[User_Id],Tarikh,Guid_Sanad
                     From Dbo.TmpSanad Where Id_Sanad=@TmpId  -- رکوردهاي جدول تمپ را به جدول اصلي سند منتقل ميکند

     If @@Error > 0  
     Begin
       ROLLBACK TRANSACTION T1
       RETURN @msg_num 
     end



    Declare Cheqe_Cursor Cursor LOCAL FOR
    SELECT   Id_Cheqe From TmpHeadC Where Id_Sanad=@TmpId
             
    OPEN Cheqe_Cursor
  
    FETCH NEXT FROM Cheqe_Cursor    INTO @Id_Cheqe

     WHILE @@FETCH_STATUS = 0     BEGIN 
         Exec  Sodor_Vajeh  @Msg_num Output ,@Id_Cheqe ,0,0 ,@Last_Id    
         FETCH NEXT FROM Cheqe_Cursor   INTO @Id_Cheqe
     End
    Close Cheqe_Cursor
    Deallocate Cheqe_Cursor

     If @@Error > 0 
     Begin
       ROLLBACK TRANSACTION T1
       RETURN @msg_num 
     end


  delete from dbo.TmpHeadS   where  Id_Sanad=@TmpId     
   
  Commit Tran T1
  
  Select @msg_num=@Last_Id
  RETURN @msg_num


End

Else 
Begin
  Set  @msg_num=-2 
  RETURN @msg_num
end
