Create Procedure Sp_CreateAccCode 
AS
Declare @Code Char(5)
Declare @Name Nvarchar(90)
Declare @Status Char(2)
Declare @AccCode Varchar(20)
Declare @Flag Char(1)
Declare @AutoId Int

Declare Cursor_Guy Cursor For
Select Guy_Code,Name,  
Case
  When Status in ('0', '2') then 20
  When Status in ('1') then 21
End As Status 
From Guy 
Open Cursor_Guy
Fetch Next From Cursor_Guy Into @Code, @Name, @Status  
While @@Fetch_Status = 0 
Begin
  ---------------------------------------------------
  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)
        Values (@AccCode + @Code , @Name, @AutoId, 3)
        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)
        Values (@AccCode + @Code , @Name, @AutoId, 3 )
        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  
  ---------------------------------------------------
  Fetch Next From Cursor_Guy Into @Code, @Name, @Status  
End 
Close Cursor_Guy
Deallocate Cursor_Guy