CREATE  procedure [dbo].[Acount_New]  @Msg_Num Smallint OutPut,@Acc_Code varchar(20),@Acc_Name nvarchar(90),@Status Char,@Class Smallint, @Force_code Bit , @saghf_Bedeh Money ,@Act_Bedeh Char , @saghf_Bestan Money ,@Act_Bestan Char
--@Msg = -1  سيستم قادر به قبول کدي با اين طول نمي باشد
--@Msg = -2 کد والد در سند داراي کارکرد ميباشد نمي توان براي آن فرزند تعريف کرد
--@Msg = -3 اين کد قبلا ايجاد شده است
--@Msg = -5  خطاي سيستم

As
  Declare @Parenet_Code Varchar(20)
  Declare @level Smallint
  Declare @P_len Smallint
  Declare @P_ID int
  If NOT Exists(Select * from Dbo.Acc_level L Where L.[len] = Len(@Acc_Code) ) 
  Begin
     Set @Msg_Num = -1
     ROLLBACK TRANSACTION A1
     RETURN @msg_num
  End 
  If (Select Count(Acc_code) from Dbo.Account Where Acc_Code=@Acc_Code) > 0 
  Begin
     Set @Msg_Num = -3
     RETURN @msg_num
  End 
  Else 
  Begin 
    Set @P_len = (Select Parent_Len from Dbo.Acc_level L Where L.[len] = Len(@Acc_Code) )
    Set @level = (Select Acc_Level from Dbo.Acc_level L Where L.[len] = Len(@Acc_Code) )
    Set @Parenet_Code = ( Select LEFT(@Acc_Code,@P_len ) )
    Set @P_ID = ( Select AutoId From dbo.Account Where Acc_Code = @Parenet_Code)
    If Exists ( Select * from Dbo.Sanad where Acc_Code = @Parenet_Code) 
    Begin 
      Set @Msg_Num = -2
      RETURN @msg_num
    End	
    Else 
    Begin
      Begin Tran A1
      If @level <> 1 
      Begin
        Insert into dbo.Account ( Acc_Code,   Acc_Name   ,Parent_Code,Acc_Level,Status  ,Class  , Force_code  ,  saghf_Bedeh , Act_Bedeh  , saghf_Bestan  , Act_Bestan ) 
                                values (@Acc_Code, @Acc_Name ,   @P_ID   ,@level   ,@Status,@Class  , @Force_code , @saghf_Bedeh ,@Act_Bedeh  , @saghf_Bestan ,@Act_Bestan)	
        If @@Error > 0  
        begin
          Set @Msg_Num = -5
          ROLLBACK TRANSACTION A1
          RETURN @msg_num
        end
      End
      Else 
      Begin
  	    Insert into dbo.Account ( Acc_Code, Acc_Name ,Parent_Code,Acc_Level,Status  ,Class  , Force_code  ,  saghf_Bedeh , Act_Bedeh  , saghf_Bestan  , Act_Bestan )
                         values (@Acc_Code, @Acc_Name ,@P_ID     ,@level   ,@Status ,@Class , @Force_code , @saghf_Bedeh ,@Act_Bedeh  , @saghf_Bestan ,@Act_Bestan)		
         If @@Error > 0 
         begin
           Set @Msg_Num = -5
           ROLLBACK TRANSACTION A1
           RETURN @msg_num
         end
       End 
       Update dbo.Account Set Has_Child = 1 Where  Acc_Code = @Parenet_Code
    End	
  End

  Commit Tran A1
  Select @msg_num=0
  RETURN @msg_num
