create PROCEDURE [dbo].[Sync_CreateSatandardDocuments]  @Id_Sanad Smallint
 AS

Truncate table sanadStandard

---------------------------------------------------------------
Declare @Acc_Code Varchar(20)
Declare @Note NVarchar(120)
Declare @Acc_Name Nvarchar(130)
Declare @type Char(1)
Declare @Bedeh Money
Declare @Bestan Money
Declare @Acc_Level Smallint
Declare @Radif Smallint

set @Radif = 1

Declare Standard_Cursor Cursor LOCAL FOR

SELECT  DocumentId,acc.Acc_Code,Sum(sa.Debtor) Bedeh, Sum(sa.Creditor) Bestan, Type, acc_name, acc_level 
From SummaryAccountingDocumentDetails sa inner join account acc on sa.code = acc.acc_code
where DocumentId = @Id_Sanad  and has_child = 0 
Group By DocumentId,acc.Acc_Code,Type, acc_name, acc_level 
order by acc.acc_code

OPEN Standard_Cursor
  
FETCH NEXT FROM Standard_Cursor INTO @Id_Sanad, @Acc_Code, @Bedeh, @Bestan, @Type, @Acc_Name, @Acc_Level

WHILE @@FETCH_STATUS = 0     
BEGIN 
  Insert Into SanadStandard (Id_Sanad,  Acc_Code,  Note,      Bedeh,  Bestan,  Type,  Acc_Level, flagInsert, Radif)  
                     VALUES (@Id_Sanad, @Acc_Code, @Acc_Name, @Bedeh, @bestan, @Type, @Acc_Level, 0, @Radif)

  set @Radif = @Radif + 2
  FETCH NEXT FROM  Standard_Cursor INTO @Id_Sanad, @Acc_Code, @bedeh, @bestan, @Type, @Acc_Name, @Acc_Level
End

Close Standard_Cursor
Deallocate Standard_Cursor

----------------------------------------------------------------------------------------------------------
Declare Standard_Cursor Cursor LOCAL FOR

SELECT  DocumentId,acc.Acc_Code, sa.Debtor, sa.Creditor, Type, Acc_Name as  Note, acc_level 
From SummaryAccountingDocumentDetails sa inner join account acc on sa.code = acc.acc_code
where DocumentId = @Id_Sanad  and has_child = 0 
order by acc.acc_code, sa.Debtor, sa.Creditor


set @Radif = 2

OPEN Standard_Cursor
  
FETCH NEXT FROM Standard_Cursor INTO @Id_Sanad, @Acc_Code, @Bedeh, @Bestan, @Type, @Acc_Name, @Acc_Level

WHILE @@FETCH_STATUS = 0     
BEGIN 
  Insert Into SanadStandard (Id_Sanad,  Acc_Code,  Note,      Bedeh,  Bestan,  Type,  Acc_Level, flagInsert, Radif)  
                     VALUES (@Id_Sanad, @Acc_Code, @Acc_Name + '   ', @Bedeh, @bestan, @Type, @Acc_Level, 1, @Radif)

  set @Radif = @Radif + 2
  FETCH NEXT FROM  Standard_Cursor INTO @Id_Sanad, @Acc_Code, @bedeh, @bestan, @Type, @Acc_Name, @Acc_Level
End

Close Standard_Cursor
Deallocate Standard_Cursor




