create Procedure [dbo].[Sp_SingleAccountingCode] @Code VARCHAR(5), @Name NVARCHAR(90) , @Status CHAR(2), @UserId Smallint
AS

  DECLARE @AccCode Varchar(20)
  DECLARE @Flag Char(1)
  DECLARE @AutoId Int

  ---------------------------------------------------
  DECLARE Cursor_Account Cursor For
  SELECT AutoId, Acc_Code From Account Where Class = @Status
  OPEN Cursor_Account
  FETCH Next From Cursor_Account Into @AutoId, @AccCode
  WHILE @@Fetch_Status = 0 
  BEGIN
    IF Exists(Select Code From Acc_Link Where Code = @Code And Acc_Code = @AccCode + @Code)
    BEGIN
      IF Not Exists(Select Acc_Code From Account Where Acc_Code = @AccCode + @Code)
      BEGIN
        Insert Into Account (Acc_Code, Acc_Name, Parent_Code, Acc_Level, User_Id)
        Values (@AccCode + @Code , @Name, @AutoId, 3, @UserId)
        IF @@Error > 0
          RollBack Tran
      End
    End
    ELSE
    BEGIN
      IF Exists(Select Acc_Code From Account Where Acc_Code = @AccCode + @Code)
      BEGIN
        IF Not Exists(Select Acc_Code From Acc_Link Where Acc_Code = @AccCode + @Code)
        BEGIN
          INSERT INTO Acc_Link (Class, Code, Acc_Code, Acc_Parent_Code)
          VALUES(@Status, @Code, @AccCode + @Code, @AccCode)
          IF @@Error > 0
            RollBack Tran
        END
      END
      Else
      BEGIN
        INSERT INTO Account (Acc_Code, Acc_Name, Parent_Code, Acc_Level, User_Id)
        VALUES (@AccCode + @Code , @Name, @AutoId, 3 , @UserId)
        IF @@Error > 0
          ROLLBACK TRAN
      
        IF Not Exists(Select Acc_Code From Acc_Link Where Acc_Code = @AccCode + @Code)
        Begin
          Insert Into Acc_Link (Class, Code, Acc_Code, Acc_Parent_Code)
          Values(@Status, @Code, @AccCode + @Code, @AccCode)
          IF @@Error > 0
            RollBack Tran
        End
     
      End
    End
    FETCH NEXT FROM Cursor_Account INTO @AutoId, @AccCode
  End
  CLOSE Cursor_Account
  DEALLOCATE Cursor_Account  
  ---------------------------------------------------
