CREATE PROCEDURE TransferOfinformationBetweenFinancialYears 
@FiscalYearSource Varchar(10),
@FiscalYearDestination VARCHAR(10), 
@StartDate VARCHAR(10), 
@EndDate VARCHAR(10),
@ExceptCompanyCode VARCHAR(MAX),
@FactorType VARCHAR(20)
AS

DECLARE @CreateTableErrorCommand NVARCHAR(MAX)
DECLARE @CacheFactorCommand NVARCHAR(MAX)
DECLARE @UnitsCommand NVARCHAR(MAX)
DECLARE @WarehouseCommand NVARCHAR(MAX)
DECLARE @GroupCommand NVARCHAR(MAX)
DECLARE @GoodsCommand NVARCHAR(MAX)
DECLARE @PersonCommand NVARCHAR(MAX)
DECLARE @BankCommand NVARCHAR(MAX)
DECLARE @IncrementalDeduction NVARCHAR(MAX)
DECLARE @RelationGoodsCommand NVARCHAR(MAX)
DECLARE @CreateFieldCommand NVARCHAR(MAX)
DECLARE @CreateLinkCommand NVARCHAR(MAX)
DECLARE @StatusTriggersCommand NVARCHAR(MAX)
DECLARE @CreateAutoAccountingDocumentCommand NVARCHAR(MAX)
DECLARE @SaveFactorCommand NVARCHAR(MAX)
DECLARE @TmpSql NVARCHAR(MAX)
 

------------------------------(Factors)---------------------------------------------------------------
SET @CreateFieldCommand = 'DECLARE @Id Int                               
	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Headh''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''Id'')
	  Alter Table [@Year].dbo.Headh Add Id UNIQUEIDENTIFIER Default(NEWID()) NOT NULL

	SELECT @Id = Id From sysobjects Where Name = ''Headh''
	IF not Exists(SELECT * FROM syscolumns WHERE id = @Id and Name = ''Sended'')
	  Alter Table dbo.Headh Add Sended Bit Default(0)
  
	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Havaleh''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''Id'')
	  Alter Table [@Year].dbo.Havaleh Add Id UNIQUEIDENTIFIER Default(NEWID()) NOT NULL

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Havaleh''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''FactorId'')
	  Alter Table [@Year].dbo.Havaleh Add FactorId UNIQUEIDENTIFIER Null

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Over_Under_Factor''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''Id'')
	  Alter Table [@Year].dbo.Over_Under_Factor Add Id UNIQUEIDENTIFIER Default(NEWID()) NOT NULL

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Over_Under_Factor''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''FactorId'')
	  Alter Table [@Year].dbo.Over_Under_Factor Add FactorId UNIQUEIDENTIFIER Null
  
	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Over_Under_Row''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''Id'')
	  Alter Table [@Year].dbo.Over_Under_Row Add Id UNIQUEIDENTIFIER Default(NEWID()) NOT NULL

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Over_Under_Row''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''ItemsId'')
	  Alter Table [@Year].dbo.Over_Under_Row Add ItemsId UNIQUEIDENTIFIER Null
  
	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Headc''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''Id'')
	  Alter Table [@Year].dbo.Headc Add Id UNIQUEIDENTIFIER Default(NEWID()) NOT NULL

	Select @Id = Id From [@Year].dbo.sysobjects Where Name = ''Headc''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''FactorId'')
	  Alter Table [@Year].dbo.Headc Add FactorId UNIQUEIDENTIFIER Null 
  
	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Cheqe''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''CashId'')
	  Alter Table [@Year].dbo.Cheqe Add CashId UNIQUEIDENTIFIER Null  

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Cheqe''
	IF not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''BankId'')
	  Alter Table [@Year].dbo.Cheqe Add BankId UNIQUEIDENTIFIER Null  

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Sanad''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''FactorId'')
	  Alter Table [@Year].dbo.Sanad Add FactorId UNIQUEIDENTIFIER Null

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Sanad''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''IncrementalDeductionId'')
	  Alter Table [@Year].dbo.Sanad Add IncrementalDeductionId UNIQUEIDENTIFIER Null

	SELECT @Id = Id From [@Year].dbo.sysobjects Where Name = ''Sanad''
	if not Exists(SELECT * FROM [@Year].dbo.syscolumns WHERE id = @Id and Name = ''CashId'')
	  Alter Table [@Year].dbo.Sanad Add CashId UNIQUEIDENTIFIER Null'

SET @CreateLinkCommand = '
	UPDATE [@Year].dbo.Havaleh  SET FactorId = Headh.Id FROM [@Year].dbo.Havaleh Havaleh
	INNER JOIN [@Year].dbo.headH headH ON headH.Id_Havaleh = Havaleh.Id_Havaleh
	Where ISNULL(FactorId,NEWID()) <> ISNULL(Headh.Id , NEWID())

	UPDATE [@Year].dbo.Over_Under_Row SET ItemsId = Havaleh.Id FROM [@Year].dbo.Over_Under_Row Over_Under_Row
	INNER JOIN [@Year].dbo.Havaleh Havaleh ON Havaleh.AutoId = Over_Under_Row.AutoId
	Where ISNULL(ItemsId,NEWID()) <> ISNULL(Havaleh.Id , NEWID())

	UPDATE [@Year].dbo.Over_Under_Factor SET FactorId = Headh.Id FROM [@Year].dbo.Over_Under_Factor Over_Under_Factor
	INNER JOIN [@Year].dbo.headH headH ON headH.Id_Havaleh = Over_Under_Factor.Id_Havaleh
	Where ISNULL(FactorId,NEWID()) <> ISNULL(Headh.Id , NEWID())

	UPDATE [@Year].dbo.Headc SET FactorId = Headh.Id FROM [@Year].dbo.Headc Headc
	INNER JOIN [@Year].dbo.headH Headh ON headH.Id_Havaleh = Headc.Id_Havaleh
	Where ISNULL(FactorId,NEWID()) <> ISNULL(Headh.Id , NEWID())

	UPDATE [@Year].dbo.Cheqe SET CashId = Headc.Id FROM [@Year].dbo.Cheqe Cheqe
	INNER JOIN [@Year].dbo.Headc Headc ON headc.Id_Cheqe = Cheqe.Id_Cheqe
	Where ISNULL(CashId,NEWID()) <> ISNULL(Headc.Id , NEWID())

	UPDATE [@Year].dbo.Sanad SET FactorId = Headh.Id FROM [@Year].dbo.Sanad Sanad
	INNER JOIN [@Year].dbo.Headh Headh ON Headh.Id_Havaleh = Sanad.Nu_Havaleh
	Where ISNULL(FactorId,NEWID()) <> ISNULL(Headh.Id , NEWID())

	UPDATE [@Year].dbo.Sanad SET IncrementalDeductionId = Over_Under_Factor.Id FROM [@Year].dbo.Sanad Sanad
	INNER JOIN [@Year].dbo.Over_Under_Factor Over_Under_Factor ON Over_Under_Factor.AutoId = Sanad.Nu_Over_Under
	Where ISNULL(IncrementalDeductionId,NEWID()) <> ISNULL(Over_Under_Factor.Id , NEWID())

	UPDATE [@Year].dbo.Sanad SET CashId = Headc.Id FROM [@Year].dbo.Sanad Sanad
	INNER JOIN [@Year].dbo.Headc Headc ON Sanad.Nu_Vajeh = Headc.Id_Cheqe
	Where ISNULL(CashId,NEWID()) <> ISNULL(Headc.Id , NEWID())'


SET @CacheFactorCommand = '
        Declare @StartDate SmallDateTime = Dbo.ShamsiToMiladi(''' + @StartDate  + ''')
        Declare @EndDate SmallDateTime = Dbo.ShamsiToMiladi('''   + @EndDate    + ''')
        Declare @FactorType Varchar(20) = '''  + @FactorType + '''
		Declare @ExceptCompanyCode Varchar(max) = '''  + @ExceptCompanyCode + '''

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##Warehouse'')
		Drop Table ##Warehouse

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##WarehouseGoods'')
		Drop Table ##WarehouseGoods

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##FactorHeader'')
		Drop Table ##FactorHeader

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##FactorDetail'')
		Drop Table ##FactorDetail

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##IncrementalDeduction'')
		Drop Table ##IncrementalDeduction

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##IncrementalDeductionRow'')
		Drop Table ##IncrementalDeductionRow

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##CashHeader'')
		Drop Table ##CashHeader

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##DocumentFactor'')
		Drop Table ##DocumentFactor

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##DocumentCash'')
		Drop Table ##DocumentCash

		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##CreateGuid'')
		Drop Table ##CreateGuid
		
		Select Id_Havaleh Into ##CreateGuid From [@FiscalYearSource].dbo.Headh
	    WHERE CONVERT(VARCHAR(10), Tarikh_faktor, 111) BETWEEN @StartDate AND @EndDate
		And Kind_Flag in(SELECT splitdata FROM dbo.fnSplitString(@FactorType,'',''))
		
		UPDATE [@FiscalYearSource].dbo.Headh Set Id = NewId() 
		Where Id_Havaleh in(Select Id_Havaleh From ##CreateGuid)
		And Id Is Null;

		UPDATE [@FiscalYearSource].dbo.Havaleh Set Id = NewId() 
		Where Id_Havaleh in(Select Id_Havaleh From ##CreateGuid)
		And Id Is Null;

		UPDATE [@FiscalYearSource].dbo.HeadC Set Id = NewId() 
		Where Id_Havaleh in(Select Id_Havaleh From ##CreateGuid)
		And Id Is Null;

		--------------------------------(Cache Factor Data)----------------------------------
		SELECT FactorHeader.Id_Havaleh, Kind_Flag, Nu_Havaleh, Nu_Resid,
					   Nu_Forosh, Nu_Kharid, Nu_Bargasht_Forosh, 
					   Nu_Bargasht_kharid, Items,
					   Number_bar, Recive_Name, Trans_Name, 
					   Tot_Price_KHarid, Tot_Price_forosh, Tot_Price_Omdeh, 
					   Tarikh_faktor, Note, User_id, Tarikh, 
					   Tarikh_Pardakht, CheckTarikh_Pardakht, 
					   Store_Code, Tot_Price_Cooperative, Kind_Cooperative, 
					   Id, Sended, UserReciver INTO ##FactorHeader  
        FROM (
				SELECT Id_Havaleh, Kind_Flag, Nu_Havaleh, Nu_Resid,
					   Nu_Forosh, Nu_Kharid, Nu_Bargasht_Forosh, 
					   Nu_Bargasht_kharid, Items,
					   Number_bar, Recive_Name, Trans_Name, 
					   Tot_Price_KHarid, Tot_Price_forosh, Tot_Price_Omdeh, 
					   Tarikh_faktor, Note, User_id, Tarikh, 
					   Tarikh_Pardakht, CheckTarikh_Pardakht, 
					   Store_Code, Tot_Price_Cooperative, Kind_Cooperative, 
					   Id, Sended, UserReciver FROM [@FiscalYearSource].dbo.Headh Headh WITH (NOLOCK)
					   WHERE CONVERT(VARCHAR(10), Tarikh_faktor, 111) BETWEEN @StartDate AND @EndDate
					   AND Headh.Kind_Flag in(SELECT splitdata FROM dbo.fnSplitString(@FactorType,'',''))
			) AS FactorHeader
			INNER JOIN
			(
			  SELECT Id_Havaleh, CompanyCode FROM(
			  SELECT Id_Havaleh, 
			  CASE
				WHEN LEN(Sender) = 3 THEN Reciver
				ELSE Sender
			  END AS CompanyCode FROM [@FiscalYearSource].dbo.Havaleh Havaleh WITH (NOLOCK)
			  ) AS T 
			  GROUP BY Id_Havaleh, CompanyCode
			  HAVING CompanyCode NOT IN(SELECT splitdata FROM dbo.fnSplitString(@ExceptCompanyCode,''-''))
			) AS FactorDetail ON FactorDetail.Id_Havaleh = FactorHeader.Id_Havaleh;

		SELECT 
			Havaleh.Id_Havaleh, AutoId, Sender, Reciver, Radif, K_Code, 
			K_Qty1, K_Qty2, R_Unit1_2, Price_KHarid, Price_Omdeh, 
			Price_Forosh, Takhfif_flag, Exp_Flag, Point_Flag, 
			Serial_Flag, Make_Flag, Hamrah_Flag, EditQty_Flag, 
			CtrMojodi, link_Record, Tot_Kharid, Tot_Forosh, Tot_Omdeh,
			Havaleh.Note, DayOfKala, Price_Consumer, Cooperative_Flag, 
			Havaleh.Id, FactorId, ChainFlag, JetId, Price_Finish, VisitorCode INTO ##FactorDetail
			FROM [@FiscalYearSource].dbo.Havaleh Havaleh WITH (NOLOCK)
			INNER JOIN ##FactorHeader ON ##FactorHeader.Id_Havaleh = Havaleh.Id_Havaleh;

		SELECT 
			Code_Over_Under, Name, Over_Under_Factor.Type, Price, [Percent], Over_Under_Factor.Act_Code, 
			Auto_Id_Havaleh, Price_Row,  Guy_Code, Over_Under_Factor.Id, FactorId Into ##IncrementalDeduction
			FROM [@FiscalYearSource].dbo.Over_Under_Factor Over_Under_Factor WITH (NOLOCK)
			INNER JOIN [@FiscalYearSource].dbo.Over_Under Over_Under WITH (NOLOCK) ON Over_Under.AutoId = Over_Under_Factor.Code_Over_Under
			INNER JOIN ##FactorHeader WITH (NOLOCK) ON ##FactorHeader.Id_Havaleh = Over_Under_Factor.Id_Havaleh;

		SELECT 
		    ##FactorDetail.Autoid,  Code_Over_Under, Over_Under_Row.Name, Over_Under_Row.Type, Price, [Percent], 
			Over_Under_Row.Max_Price, Over_Under_Row.Max_Percent,
			Over_Under_Row.Id, Over_Under_Row.ItemsId Into ##IncrementalDeductionRow
			FROM [@FiscalYearSource].dbo.Over_Under_Row Over_Under_Row WITH (NOLOCK)
			INNER JOIN [@FiscalYearSource].dbo.Over_Under Over_Under WITH (NOLOCK) ON Over_Under.AutoId = Over_Under_Row.Code_Over_Under
			INNER JOIN ##FactorDetail WITH (NOLOCK) ON ##FactorDetail.Autoid = Over_Under_Row.Autoid;

		SELECT 
		    ##FactorHeader.Id_Havaleh, Headc.Id_Cheqe, Headc.Kind_Flag, TarikhBargeh, Guy_Code, Headc.Tarikh, Guy_Bank, AccCode, Headc.Id, FactorId INTO ##CashHeader
		    FROM [@FiscalYearSource].dbo.Headc Headc WITH (NOLOCK)
		    INNER JOIN ##FactorHeader WITH (NOLOCK) ON  ##FactorHeader.Id_Havaleh = HeadC.Id_Havaleh

        SELECT 
		   Type, Acc_Code, Sanad.Note, RADIF, BEDEH, Bestan, Edit_FLag, Auto_Create, Sanad.User_ID, Sanad.Tarikh,  
		   Nu_Cooperative, ##FactorHeader.Tarikh_Faktor FactorDate, FactorId,  IncrementalDeductionId, CashId Into ##DocumentFactor 
		   FROM [@FiscalYearSource].dbo.Sanad Sanad WITH (NOLOCK)
           Inner join ##FactorHeader on Sanad.Nu_Havaleh = ##FactorHeader.Id_Havaleh
		
		SELECT 
			Type, Acc_Code, Sanad.Note, RADIF, BEDEH, Bestan, Edit_FLag, Auto_Create, Sanad.User_ID, Sanad.Tarikh,  
			Nu_Cooperative, ##FactorHeader.Tarikh_Faktor FactorDate, Sanad.FactorId,  IncrementalDeductionId, CashId Into ##DocumentCash
			FROM [@FiscalYearSource].dbo.Sanad Sanad WITH (NOLOCK)
			Inner join ##CashHeader on Sanad.Nu_Vajeh = ##CashHeader.Id_Cheqe
			INNER JOIN ##FactorHeader ON ##FactorHeader.Id_Havaleh = ##CashHeader.Id_Havaleh'

		--------------------------------(Cache Factor Data)----------------------------------'
SET @IncrementalDeduction = '
		--------------------------------------------(IncrementalDeduction)---------------------------
		INSERT INTO [@FiscalYearDestination].dbo.Over_Under(Name,Type,Max_Price,Max_Percent,Formula,AzTarikh,TaTarikh, Active,ShowPrice,Action_Code,Act_Code,Tarikh,User_Id,SortDisplay,Store_Code,StoreCode,Duty_Flag,PurchaseAction)
		SELECT Name,Type,Max_Price,Max_Percent,Formula,AzTarikh,
		TaTarikh, Active,ShowPrice,Action_Code,Act_Code,Tarikh,User_Id,
		SortDisplay,Store_Code,StoreCode,Duty_Flag,PurchaseAction FROM [@FiscalYearSource].dbo.Over_Under AS T WITH (NOLOCK)
		WHERE REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Over_Under WITH (NOLOCK))'

SET @UnitsCommand = '
		--------------------------------------------(Units)----------------------------------
		INSERT INTO [@FiscalYearDestination].dbo.Unit1(Name)
		SELECT REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Name FROM [@FiscalYearSource].dbo.Unit1 AS T
		WHERE REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Unit1 WITH (NOLOCK))
		GROUP BY REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705));

		INSERT INTO [@FiscalYearDestination].dbo.Unit2(Name)
		SELECT REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Name FROM [@FiscalYearSource].dbo.Unit2 AS T
		WHERE REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Unit2 WITH (NOLOCK))
		GROUP BY REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705));

		INSERT INTO [@FiscalYearDestination].dbo.Unit3(Name)
		SELECT REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Name FROM [@FiscalYearSource].dbo.Unit3 AS T
		WHERE REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Unit3 WITH (NOLOCK))
		GROUP BY REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705));'

SET @GroupCommand = '
		--------------------------------------------(Group)-----------------------------------------------
		DECLARE @Code INT
		DECLARE @Name NVARCHAR(50)
		DECLARE @CacheName NVARCHAR(50)
		DECLARE @Parent INT
		DECLARE CursorGroup CURSOR FOR
		SELECT T.Gid, T.GName, T.Parent FROM [@FiscalYearSource].dbo.Group1 AS T
		WHERE T.GName NOT IN(SELECT GName FROM [@FiscalYearDestination].dbo.Group1 WITH (NOLOCK))
		OPEN CursorGroup
		FETCH NEXT FROM CursorGroup INTO @Code, @Name, @Parent
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF NOT EXISTS(SELECT Gname FROM dbo.Group1 WHERE Gname = @Name)
			BEGIN 
				IF @Parent = 0 
				INSERT INTO [@FiscalYearDestination].dbo.Group1(Gname,Parent) VALUES(@Name, @Parent) 
				ELSE
				BEGIN
				SELECT @CacheName = GName FROM [@FiscalYearSource].dbo.Group1 WHERE Gid = @Parent
  				SELECT @Code = Gid FROM [@FiscalYearDestination].dbo.Group1 WHERE Gname = @CacheName
				INSERT INTO [@FiscalYearDestination].dbo.Group1(Gname,Parent) VALUES(@Name, @Code) 
				END
			END 
			FETCH NEXT FROM CursorGroup INTO @Code, @Name, @Parent
		END
		CLOSE CursorGroup
		DEALLOCATE CursorGroup'

SET @WarehouseCommand = '
		--------------------------------------------(Warehouses)-------------------------------------------
		DECLARE @CompanyName NVARCHAR(60) = (SELECT Name FROM [@FiscalYearSource].dbo.Cooprations)
		SELECT AnbarId.A_Code, Name,CtrMojodi,Store_Code,NatureWarehouse,NatureWarehouseGoods INTO ##Warehouse
		FROM (
				SELECT Sender A_Code FROM ##FactorDetail
				WHERE LEN(Sender) = 3
				GROUP BY Sender 
				UNION 
				SELECT Reciver A_Code FROM ##FactorDetail
				Where LEN(Reciver) = 3
				GROUP BY Reciver
			) AS WareHouse
			INNER JOIN [@FiscalYearSource].dbo.AnbarId AnbarId ON AnbarId.A_Code = WareHouse.A_Code

		INSERT INTO [@FiscalYearDestination].dbo.AnbarId(A_Code,Name,CtrMojodi,Store_Code,NatureWarehouse,NatureWarehouseGoods)
		SELECT A_Code,Name,CtrMojodi,Store_Code,NatureWarehouse,NatureWarehouseGoods FROM ##Warehouse 
		WHERE [##Warehouse].A_Code NOT IN(SELECT A_Code FROM [@FiscalYearDestination].dbo.AnbarId WITH (NOLOCK)) 
		AND [##Warehouse].Name NOT IN(SELECT Name FROM [@FiscalYearDestination].dbo.AnbarId WITH (NOLOCK))
		UNION  
		SELECT A_Code,SUBSTRING(Name + ''_'' + @CompanyName ,1,30),CtrMojodi,Store_Code,NatureWarehouse,NatureWarehouseGoods FROM ##Warehouse 
		WHERE [##Warehouse].A_Code NOT IN(SELECT A_Code FROM [@FiscalYearDestination].dbo.AnbarId WITH (NOLOCK))
		AND [##Warehouse].Name IN(SELECT Name FROM [@FiscalYearDestination].dbo.AnbarId WITH (NOLOCK));
		--------------------------------------------(WarehouseGoods)----------------------------------
		SELECT A_Code,K_Code,Reserve,kala_Min,Kala_Max,Price_Kharid,Price_Omdeh,Price_Forosh,
		Active_Flag,Saghf_Forosh, LocateKala, Price_Consumer,DayKharid, DayForosh,DayOmdeh,
		DayConsumer,User_Id, Note,Price_Finish, Charg_Flag,Price_Internet INTO ##WarehouseGoods FROM (
		SELECT T.A_Code,T.K_Code,Reserve,kala_Min,Kala_Max,T.Price_Kharid,T.Price_Omdeh,T.Price_Forosh,
		Active_Flag,Saghf_Forosh, LocateKala, T.Price_Consumer,DayKharid, DayForosh,DayOmdeh,
		DayConsumer,User_Id, T.Note,T.Price_Finish, Charg_Flag,Price_Internet FROM [@FiscalYearSource].dbo.Anbar AS T WITH (NOLOCK)
		INNER JOIN ##FactorDetail ON ##FactorDetail.K_Code = T.K_Code AND ##FactorDetail.Sender = T.A_Code
		UNION 
		SELECT A_Code,T.K_Code,Reserve,kala_Min,Kala_Max,T.Price_Kharid,T.Price_Omdeh,T.Price_Forosh,
		Active_Flag,Saghf_Forosh, LocateKala, T.Price_Consumer,DayKharid, DayForosh,DayOmdeh,
		DayConsumer,User_Id, T.Note,T.Price_Finish, Charg_Flag,Price_Internet FROM [@FiscalYearSource].dbo.Anbar AS T WITH (NOLOCK)
		INNER JOIN ##FactorDetail ON ##FactorDetail.K_Code = T.K_Code AND ##FactorDetail.Reciver = T.A_Code
		GROUP BY T.A_Code,T.K_Code,Reserve,kala_Min,Kala_Max,T.Price_Kharid,T.Price_Omdeh,T.Price_Forosh,
		Active_Flag,Saghf_Forosh, LocateKala, T.Price_Consumer,DayKharid, DayForosh,DayOmdeh,
		DayConsumer,User_Id, T.Note,T.Price_Finish, Charg_Flag,Price_Internet
		) AS WarehouseGoods 

		INSERT INTO [@FiscalYearDestination].dbo.Anbar(A_Code,K_Code,Reserve,kala_Min,Kala_Max,Price_Kharid,Price_Omdeh,Price_Forosh,
							Active_Flag,Saghf_Forosh, LocateKala, Price_Consumer,DayKharid, DayForosh,DayOmdeh,
							DayConsumer,User_Id, Note,Price_Finish, Charg_Flag,Price_Internet)
		SELECT A_Code,K_Code,Reserve,kala_Min,Kala_Max,Price_Kharid,Price_Omdeh,Price_Forosh,
							Active_Flag,Saghf_Forosh, LocateKala, Price_Consumer,DayKharid, DayForosh,DayOmdeh,
							DayConsumer,User_Id, Note,Price_Finish, Charg_Flag,Price_Internet FROM ##WarehouseGoods
		WHERE NOT EXISTS(SELECT * FROM [@FiscalYearDestination].dbo.anbar AS T1 WITH (NOLOCK) WHERE ##WarehouseGoods.K_Code = T1.K_Code AND ##WarehouseGoods.A_Code = T1.A_Code)
		AND ##WarehouseGoods.K_Code IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.Kalaid WITH (NOLOCK))'

SET @GoodsCommand = '
		---------------------------------(GoodsCode)--------------------------------------
		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##GoodsCode'')
		Drop Table ##GoodsCode

		DECLARE @CompanyName NVARCHAR(60) = (SELECT Name FROM [@FiscalYearSource].dbo.Cooprations)
		SELECT Goods.K_Code,Barcode,M_Code,Name1 ,Name2,Goods.R_Unit1_2,R_Unit1_3,Goods.Point_Flag,Goods.Serial_flag, 
				Goods.Exp_Flag, Darou_Flag, Goods.Make_Flag, Goods.Hamrah_Flag, Goods.CtrMojodi, User_Id, Tarikh,  Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType , 
				REPLACE(REPLACE(Unit1.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Unit1Name,
				REPLACE(REPLACE(Unit2.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Unit2Name,
				REPLACE(REPLACE(Unit3.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) Unit3Name INTO ##GoodsCode
				FROM [@FiscalYearSource].dbo.KalaId AS Goods WITH (NOLOCK)
				INNER JOIN ##FactorDetail ON ##FactorDetail.K_Code = Goods.K_Code
				INNER JOIN [@FiscalYearSource].dbo.Unit1 Unit1 WITH (NOLOCK) ON Unit1.U_Code1 = Goods.U_Code1
				LEFT  JOIN [@FiscalYearSource].dbo.Unit2 Unit2 WITH (NOLOCK) ON Unit2.U_Code2 = Goods.U_Code2
				LEFT  JOIN [@FiscalYearSource].dbo.Unit3 Unit3 WITH (NOLOCK) ON Unit3.U_Code3 = Goods.U_Code3
				GROUP BY Goods.K_Code,Barcode,M_Code,Name1 ,Name2,Goods.R_Unit1_2,R_Unit1_3,Goods.Point_Flag,Goods.Serial_flag, 
				Goods.Exp_Flag, Darou_Flag, Goods.Make_Flag, Goods.Hamrah_Flag, Goods.CtrMojodi, User_Id, Tarikh, Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType , 
				Unit1.Name , Unit2.Name ,Unit3.Name

		INSERT INTO [@FiscalYearDestination].dbo.Kalaid(K_Code,Barcode,M_Code,Name1,Name2,U_Code1,U_Code2,U_Code3,R_Unit1_2,R_Unit1_3,Point_Flag,Serial_flag, 
				Exp_Flag, Darou_Flag, Make_Flag, Hamrah_Flag, CtrMojodi, User_Id, Tarikh, Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType )

		SELECT K_Code,Barcode,M_Code,Name1 ,Name2,CurUnit1.U_Code1,CurUnit2.U_Code2,CurUnit3.U_Code3,R_Unit1_2,R_Unit1_3,Point_Flag,Serial_flag, 
				Exp_Flag, Darou_Flag, Make_Flag, Hamrah_Flag, CtrMojodi, User_Id, Tarikh, Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType 
				FROM (
		SELECT K_Code,Barcode,M_Code,Name1 ,Name2,R_Unit1_2,R_Unit1_3,Point_Flag,Serial_flag, 
				Exp_Flag, Darou_Flag, Make_Flag, Hamrah_Flag, CtrMojodi, User_Id, Tarikh, Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType , 
				Unit1Name,	Unit2Name,Unit3Name
				FROM ##GoodsCode
				WHERE K_Code NOT IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.KalaId WITH (NOLOCK))
				AND REPLACE(REPLACE(Name1, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name1, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.KalaId WITH (NOLOCK))
		UNION 
		SELECT K_Code,Barcode,M_Code,SUBSTRING(Name1 + ''_'' + @CompanyName  ,1,100) ,Name2,R_Unit1_2,R_Unit1_3,Point_Flag,Serial_flag, 
				Exp_Flag, Darou_Flag, Make_Flag, Hamrah_Flag, CtrMojodi, User_Id, Tarikh, Duty_Flag,Gid_Fk, 
				Visitor_Percent, Eshop_Flag,CalcFormul, Gid_Fk1,Gid_Fk2,LatinOrIr, Mosharekati_Percent, MinQtyTelegram,  MadeType,
				Unit1Name,Unit2Name,Unit3Name
				FROM ##GoodsCode
		WHERE K_Code NOT IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.KalaId WITH (NOLOCK))
		AND REPLACE(REPLACE(Name1, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) IN(SELECT REPLACE(REPLACE(Name1, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.KalaId WITH (NOLOCK))
		) AS T
		INNER JOIN [@FiscalYearDestination].dbo.Unit1 CurUnit1 ON REPLACE(REPLACE(CurUnit1.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) = T.unit1Name
		LEFT  JOIN [@FiscalYearDestination].dbo.Unit2 CurUnit2 ON REPLACE(REPLACE(CurUnit2.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) = T.unit2Name
		LEFT  JOIN [@FiscalYearDestination].dbo.Unit3 CurUnit3 ON REPLACE(REPLACE(CurUnit3.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) = T.unit3Name;'

SET @RelationGoodsCommand = '
		---------------------------------(BasketGoods)--------------------------------------
		INSERT INTO [@FiscalYearDestination].dbo.TblBasket_Kala(K_Code, K_Code_B, K_Qty1)
		SELECT K_Code, K_Code_B, K_Qty1 FROM [@FiscalYearSource].dbo.TblBasket_Kala AS T WITH (NOLOCK) 
		WHERE NOT EXISTS(SELECT * FROM [@FiscalYearDestination].dbo.TblBasket_Kala AS T1 WITH (NOLOCK) WHERE T.K_Code = T1.K_Code)
		AND T.K_Code IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.Kalaid WITH (NOLOCK))

		-------------------------------------------(GoodsAlong)------------------------------------------
		INSERT INTO [@FiscalYearDestination].dbo.Hamrah_Kala(K_Code,K_Code_H,K_Qty1,EditQty_Flag, Qty_K_Code, A_Code_H, Price_K_Code_H,Note)
		SELECT K_Code,K_Code_H,K_Qty1,EditQty_Flag, Qty_K_Code, A_Code_H, Price_K_Code_H,Note FROM [@FiscalYearSource].dbo.Hamrah_Kala AS T WITH (NOLOCK) 
		WHERE NOT EXISTS(SELECT * FROM [@FiscalYearDestination].dbo.Hamrah_Kala AS T1 WITH (NOLOCK) WHERE T.K_Code = T1.K_Code)
		AND T.K_Code IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.Kalaid WITH (NOLOCK))

		-------------------------------------------(GoodsMake)-----------------------------------------
		INSERT INTO [@FiscalYearDestination].dbo.make_Kala(K_Code, Sender, K_Code_M, Account_unit1, EditQty_Flag, PriceRasio)
		SELECT K_Code, Sender, K_Code_M, Account_unit1, EditQty_Flag, PriceRasio FROM [@FiscalYearSource].dbo.Make_Kala AS T 
		WHERE NOT EXISTS(SELECT * FROM [@FiscalYearDestination].dbo.Make_Kala AS T1 WITH (NOLOCK) WHERE T.K_Code = T1.K_Code)
		AND T.K_Code IN(SELECT K_Code FROM [@FiscalYearDestination].dbo.Kalaid WITH (NOLOCK))'

SET @PersonCommand = '
		IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##Person'')
		Drop Table ##Person

		Declare @Code Char(5)
		Declare @Name Nvarchar(90)
		Declare @Status TINYINT
		Declare @AccCode Varchar(20)
		Declare @Flag Char(1)
		Declare @AutoId INT

		DECLARE @CompanyName NVARCHAR(60) = (SELECT Name FROM [@FiscalYearSource].dbo.Cooprations)
		SELECT Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
			   Fax, Mail,Web,Postal_Code, National_Code, mobile,CAST(T.Note AS NVARCHAR(200)) Note,Show_Note_In_Factor,Status, Class,User_id,
			   Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
			   Store_Code,AccountNumber, BankName, RegNumber INTO ##Person FROM [@FiscalYearSource].dbo.Guy AS T WITH (NOLOCK)
			   INNER JOIN ##FactorDetail ON ##FactorDetail.Sender = T.Guy_Code
			   GROUP BY Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
			   Fax, Mail,Web,Postal_Code, National_Code, mobile,CAST(T.Note AS NVARCHAR(200)),Show_Note_In_Factor,Status, Class,User_id,
			   Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
			   Store_Code,AccountNumber, BankName, RegNumber

  	    UNION 
        
		SELECT Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
			   Fax, Mail,Web,Postal_Code, National_Code, mobile,CAST(T.Note AS NVARCHAR(200)) Note,Show_Note_In_Factor,Status, Class,User_id,
			   Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
			   Store_Code,AccountNumber, BankName, RegNumber FROM [@FiscalYearSource].dbo.Guy AS T WITH (NOLOCK)
			   INNER JOIN ##FactorDetail ON ##FactorDetail.Reciver = T.Guy_Code
			   GROUP BY Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
			   Fax, Mail,Web,Postal_Code, National_Code, mobile,CAST(T.Note AS NVARCHAR(200)),Show_Note_In_Factor,Status, Class,User_id,
			   Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
			   Store_Code,AccountNumber, BankName, RegNumber

			INSERT INTO [@FiscalYearDestination].dbo.Guy(Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
								Fax, Mail,Web,Postal_Code, National_Code, mobile,Note,Show_Note_In_Factor,Status, Class,User_id,
								Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
								Store_Code,AccountNumber, BankName, RegNumber)

			SELECT Guy_Code,Private_Code, M_Code, Name, Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
								Fax, Mail,Web,Postal_Code, National_Code, mobile,Note,Show_Note_In_Factor,Status, Class,User_id,
								Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
								Store_Code,AccountNumber, BankName, RegNumber FROM ##Person
			WHERE Guy_Code NOT IN(SELECT Guy_Code FROM [@FiscalYearDestination].dbo.Guy WITH (NOLOCK))
			AND REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Guy WITH (NOLOCK))
			UNION 
			SELECT Guy_Code,Private_Code, M_Code, SUBSTRING(Name + ''_'' + @CompanyName ,1,90), Addr, Tel,Ostan_Code,Act_Group,Tax_Code,Office_Adr,Office_Tel,
								Fax, Mail,Web,Postal_Code, National_Code, mobile,Note,Show_Note_In_Factor,Status, Class,User_id,
								Tarikh,F_Active, X,Y,CalcFormul, Member_Count, Visitor_Code, CartOnly, economic_code, SmsFlag,
								Store_Code,AccountNumber, BankName, RegNumber FROM ##Person
			WHERE Guy_Code NOT IN(SELECT Guy_Code FROM [@FiscalYearDestination].dbo.Guy WITH (NOLOCK))
			AND REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.Guy WITH (NOLOCK))

			Declare CursorPerson Cursor For
			Select Guy_Code,Name,  
			Case
				When Status in (0, 2) then 20
				When Status in (1) then 21
			End As Status 
			FROM ##Person 
			OPEN CursorPerson
			FETCH NEXT FROM CursorPerson Into @Code, @Name, @Status
			While @@Fetch_Status = 0 
			Begin
				---------------------------------------------------
				Declare CursorAccount Cursor For
				Select AutoId, Acc_Code From [@FiscalYearDestination].dbo.Account WITH (NOLOCK) Where Class = @Status
				Open CursorAccount
				Fetch Next From CursorAccount Into @AutoId, @AccCode
				While @@Fetch_Status = 0 
				Begin
					IF Exists(Select Acc_Code From [@FiscalYearDestination].dbo.Account WITH (NOLOCK) Where Acc_Code = @AccCode + @Code)
					Begin
					IF Not Exists(Select Acc_Code From [@FiscalYearDestination].dbo.Acc_Link WITH (NOLOCK) Where Acc_Code = @AccCode + @Code)
					Begin
						Insert Into [@FiscalYearDestination].dbo.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 [@FiscalYearDestination].dbo.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 [@FiscalYearDestination].dbo.Acc_Link WITH (NOLOCK) Where Acc_Code = @AccCode + @Code)
					Begin
						Insert Into [@FiscalYearDestination].dbo.Acc_Link (Class, Code, Acc_Code, Acc_Parent_Code)
						Values(@Status, @Code, @AccCode + @Code, @AccCode)
						IF @@Error > 0
						RollBack Tran
					End
     
					End
				Fetch Next From CursorAccount Into @AutoId, @AccCode
				End
				Close CursorAccount
				Deallocate CursorAccount  

				---------------------------------------------------
				Fetch Next From CursorPerson Into @Code, @Name, @Status
			End 
			Close CursorPerson
			Deallocate CursorPerson '
SET @BankCommand = 
            'Declare @Code Char(5)
			Declare @Name Nvarchar(90)
			Declare @Class TINYINT
			Declare @AccCode Varchar(20)
			Declare @ParentCode Varchar(20)
			Declare @AutoId INT

			IF Exists(Select * From [tempdb].dbo.sysobjects Where Name = ''##Bank'')
			Drop Table ##Bank

			SELECT T.Name, T.Address, T.phone, T.class INTO ##Bank FROM [@FiscalYearSource].dbo.Bank AS T
			WHERE REPLACE(REPLACE(T.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) NOT IN(SELECT REPLACE(REPLACE(Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) FROM [@FiscalYearDestination].dbo.bank WITH (NOLOCK))

			INSERT INTO [@FiscalYearDestination].dbo.Bank(Name,Address,phone,Class)
			SELECT Name, Address, phone, class FROM ##Bank

			Declare CursorBank Cursor For
			Select T.AutoId,T.Name, T.Class 
			FROM ##Bank
			INNER JOIN [@FiscalYearDestination].dbo.Bank AS T ON T.Name = ##Bank.Name
			WHERE T.Class = 40
			OPEN CursorBank
			FETCH NEXT FROM CursorBank Into @Code, @Name, @Class
			While @@Fetch_Status = 0 
			Begin
				---------------------------------------------------
				Declare CursorAccount Cursor For
				Select AutoId, Acc_Code From [@FiscalYearDestination].dbo.Account WITH (NOLOCK) Where Class = 40
				Open CursorAccount
				Fetch Next From CursorAccount Into @AutoId, @ParentCode
				While @@Fetch_Status = 0 
				BEGIN
					SET @AccCode = @ParentCode  + REPLICATE(''0'',5-(LEN(@Code))) + CAST(@Code AS VARCHAR(10))  
					IF Exists(Select Acc_Code From [@FiscalYearDestination].dbo.Account WITH (NOLOCK) Where Acc_Code = @AccCode)
					Begin
						IF Not Exists(Select Acc_Code From [@FiscalYearDestination].dbo.Acc_Link WITH (NOLOCK) Where Acc_Code = @AccCode)
						Begin
							Insert Into [@FiscalYearDestination].dbo.Acc_Link (Class, Code, Acc_Code, Acc_Parent_Code)
							Values(@Class, @Code, @AccCode , @ParentCode)
							IF @@Error > 0
							RollBack Tran
						End
					End
					Else
					Begin
						INSERT INTO [@FiscalYearDestination].dbo.Account (Acc_Code, Acc_Name, Parent_Code, Acc_Level)
						VALUES (@AccCode , @Name, @AutoId, 3 )
						IF @@Error > 0
							RollBack Tran
      
						IF Not Exists(Select Acc_Code From [@FiscalYearDestination].dbo.Acc_Link WITH (NOLOCK) Where Acc_Code = @AccCode)
						Begin
							INSERT INTO [@FiscalYearDestination].dbo.Acc_Link (Class, Code, Acc_Code, Acc_Parent_Code)
							VALUES(@Class, @Code, @AccCode , @ParentCode)
							IF @@Error > 0
								ROLLBACK Tran
						End
					End
					FETCH Next From CursorAccount Into @AutoId, @ParentCode
				End
				Close CursorAccount
				Deallocate CursorAccount  

				---------------------------------------------------
				Fetch Next From CursorBank Into @Code, @Name, @Class
			End 
			Close CursorBank
			Deallocate CursorBank' 


SET @StatusTriggersCommand = '
	CREATE PROCEDURE [dbo].[Sp_DisableTrigger] @StatusName VARCHAR(8) , @TablesName varchar(MAX), @NameOfTrigger varchar(MAX)
	AS
	BEGIN 
	DECLARE @TriggerName VARCHAR(MAX)
	DECLARE @TableName VARCHAR(MAX)
	DECLARE @sqlCommand VARCHAR(Max)

	DECLARE CursorDisableTrigger CURSOR FOR
	SELECT [so].[name] AS [trigger_name],
		   OBJECT_NAME([so].[parent_obj]) AS [table_name]
	FROM sysobjects AS [so]
	INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
	WHERE [so].[type] = ''TR'' AND OBJECTPROPERTY( [so].[id], @NameOfTrigger) = 1
	AND OBJECT_NAME([so].[parent_obj]) IN(SELECT splitdata FROM dbo.fnSplitString(@TablesName,'',''))
	OPEN CursorDisableTrigger
	FETCH NEXT FROM CursorDisableTrigger INTO @TriggerName, @TableName
	WHILE @@FETCH_STATUS = 0
	BEGIN
	  EXEC (''ALTER TABLE '' + @TableName + '' '' + @StatusName + '' Trigger '' + @TriggerName)
	  FETCH NEXT FROM CursorDisableTrigger INTO @TriggerName, @TableName
	END 
	CLOSE CursorDisableTrigger
	DEALLOCATE CursorDisableTrigger
	End'

SET @CreateAutoAccountingDocumentCommand = '
	DECLARE @MaxNu INT = (SELECT ISNULL(MAX(Nu_Manual),0)+ 1 FROM Heads)
	INSERT INTO [@Year].dbo.Heads(Nu_Manual, Tarikh_User, Note)
	SELECT DocNumber, DocumentDate, DocumentDesc FROM (
	SELECT ROW_NUMBER() OVER (ORDER BY Tarikh_Faktor) + @MaxNu DocNumber, Tarikh_Faktor DocumentDate, N'' Ϙ  '' + ShamsiDate DocumentDesc, 1 IsAuto FROM ##FactorHeader
	INNER JOIN dbo.Tbl_Dates ON Date = CONVERT(VARCHAR(10), Tarikh_Faktor,111)
	GROUP BY Tarikh_Faktor, ShamsiDate
	) AS T WHERE NOT EXISTS(SELECT Id_Sanad FROM [@Year].dbo.HeadS WHERE Auto = 1 AND DocumentDate = CONVERT(VARCHAR(10), Tarikh_User,111));'

SET @SaveFactorCommand ='
	INSERT INTO [@FiscalYearDestination].dbo.headH(Kind_Flag, Nu_Havaleh, Nu_Resid,
						  Nu_Forosh, Nu_Kharid, Nu_Bargasht_Forosh, 
						  Nu_Bargasht_kharid, Items,
						  Number_bar, Recive_Name, Trans_Name, 
						  Tot_Price_KHarid, Tot_Price_forosh, Tot_Price_Omdeh, 
						  Tarikh_faktor, Note, User_id, Tarikh, 
						  Tarikh_Pardakht, CheckTarikh_Pardakht, 
						  Store_Code, Tot_Price_Cooperative, Kind_Cooperative, 
						  Id, Sended, UserReciver)
	SELECT  Kind_Flag, Nu_Havaleh, Nu_Resid,
						  Nu_Forosh, Nu_Kharid, Nu_Bargasht_Forosh, 
						  Nu_Bargasht_kharid, Items,
						  Number_bar, Recive_Name, Trans_Name, 
						  Tot_Price_KHarid, Tot_Price_forosh, Tot_Price_Omdeh, 
						  Tarikh_faktor, Note, User_id, Tarikh, 
						  Tarikh_Pardakht, CheckTarikh_Pardakht, 
						  Store_Code, Tot_Price_Cooperative, Kind_Cooperative, 
						  Id, Sended, UserReciver FROM ##FactorHeader
						  WHERE Id NOT IN(SELECT Id FROM [@FiscalYearDestination].dbo.Headh WITH (NOLOCK) WHERE Id IS NOT null);
	DECLARE @RowId BIGINT
	SET @RowId = IDENT_CURRENT(''TmpHavaleh'') 
	INSERT INTO [@FiscalYearDestination].dbo.Havaleh(Havaleh.Id_Havaleh, AutoId, Sender, Reciver, Radif, K_Code, 
							K_Qty1, K_Qty2, R_Unit1_2, Price_KHarid, Price_Omdeh, 
							Price_Forosh, Takhfif_flag, Exp_Flag, Point_Flag, 
							Serial_Flag, Make_Flag, Hamrah_Flag, EditQty_Flag, 
							CtrMojodi, link_Record, Tot_Kharid, Tot_Forosh, Tot_Omdeh,
							Havaleh.Note, DayOfKala, Price_Consumer, Cooperative_Flag, 
							Havaleh.Id, FactorId, ChainFlag, JetId, Price_Finish, VisitorCode)
	SELECT Headh.Id_Havaleh, ROW_NUMBER() OVER(ORDER BY ##FactorDetail.Id)+ @RowId  AutoId, Sender, Reciver, Radif, K_Code, 
							K_Qty1, K_Qty2, R_Unit1_2, Price_KHarid, Price_Omdeh, 
							Price_Forosh, Takhfif_flag, Exp_Flag, Point_Flag, 
							Serial_Flag, Make_Flag, Hamrah_Flag, EditQty_Flag, 
							CtrMojodi, link_Record, Tot_Kharid, Tot_Forosh, Tot_Omdeh,
							Substring(##FactorHeader.Note,1,60), DayOfKala, Price_Consumer, Cooperative_Flag, 
							##FactorDetail.Id, FactorId, ChainFlag, JetId, Price_Finish, VisitorCode FROM ##FactorDetail
							INNER JOIN ##FactorHeader ON ##FactorHeader.Id = ##FactorDetail.FactorId
							INNER JOIN Headh WITH (NOLOCK) ON ##FactorHeader.Id = Headh.Id
							WHERE ##FactorDetail.Id NOT IN(SELECT Id FROM [@FiscalYearDestination].dbo.Havaleh WITH (NOLOCK) WHERE Id IS NOT null);

	INSERT INTO [@FiscalYearDestination].dbo.Over_Under_Factor(Id_Havaleh, Code_Over_Under, Type, Price, [Percent], Act_Code, Auto_Id_Havaleh, Price_Row,  Guy_Code, Id, FactorId)
	SELECT Headh.Id_Havaleh, ou.AutoId, ##IncrementalDeduction.Type, Price, [Percent], ##IncrementalDeduction.Act_Code, 
	Auto_Id_Havaleh, Price_Row,  Guy_Code, ##IncrementalDeduction.Id, FactorId FROM ##IncrementalDeduction
	INNER JOIN Headh WITH (NOLOCK) ON Headh.Id = ##IncrementalDeduction.FactorId
	INNER JOIN [@FiscalYearDestination].dbo.Over_Under AS OU ON 
	REPLACE(REPLACE(Ou.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) = REPLACE(REPLACE(##IncrementalDeduction.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705))
	WHERE ##IncrementalDeduction.Id NOT IN(SELECT Id FROM [@FiscalYearDestination].dbo.Over_Under_Factor WITH (NOLOCK) WHERE Id IS NOT null);

	INSERT INTO [@FiscalYearDestination].dbo.Over_Under_Row(Autoid,  Code_Over_Under, Name, Type, Price, [Percent], Max_Price, Max_Percent,Id, ItemsId)
	SELECT Havaleh.AutoId, ou.AutoId, ##IncrementalDeductionRow.Name, ##IncrementalDeductionRow.Type, Price, [Percent], 
	##IncrementalDeductionRow.Max_Price, ##IncrementalDeductionRow.Max_Percent, ##IncrementalDeductionRow.Id, ItemsId FROM ##IncrementalDeductionRow
	INNER JOIN Havaleh WITH (NOLOCK) ON Havaleh.Id = ##IncrementalDeductionRow.ItemsId
	INNER JOIN [@FiscalYearDestination].dbo.Over_Under AS OU ON 
	REPLACE(REPLACE(Ou.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705)) = REPLACE(REPLACE(##IncrementalDeductionRow.Name, Nchar(1610), Nchar(1740)),Nchar(1603), Nchar(1705))
	WHERE ##IncrementalDeductionRow.Id NOT IN(SELECT Id FROM [@FiscalYearDestination].dbo.Over_Under_Row WITH (NOLOCK) WHERE Id IS NOT null);

	DECLARE @MaxNu INT = (SELECT ISNULL(MAX(Id_Manual),0) FROM [@FiscalYearDestination].dbo.Headc WITH (NOLOCK))
	INSERT INTO [@FiscalYearDestination].dbo.HeadC(Id_Havaleh, Id_Manual, Kind_Flag, TarikhBargeh, Guy_Code, Tarikh, Guy_Bank, AccCode, Id, FactorId)
	SELECT Headh.Id_Havaleh, ROW_NUMBER() OVER(ORDER BY ##CashHeader.Id)+ @MaxNu , ##CashHeader.Kind_Flag, TarikhBargeh, Guy_Code, ##CashHeader.Tarikh, Guy_Bank, AccCode, ##CashHeader.Id, FactorId FROM ##CashHeader
	INNER JOIN Headh WITH (NOLOCK) ON Headh.Id = ##CashHeader.FactorId
	WHERE ##CashHeader.Id NOT IN(SELECT Id FROM [@FiscalYearDestination].dbo.Headc WITH (NOLOCK) WHERE Id IS NOT null);

    INSERT INTO [@FiscalYearDestination].dbo.Cheqe(Headc.Id_Cheqe, Ch_Tarikh, Ch_price, Ch_note, Ch_no, Ch_pass, Act_Code, Ch_bank, CashId)
	SELECT Headc.Id_Cheqe, Ch_Tarikh, Ch_price, Ch_note, Ch_no, Ch_pass, Act_Code, Ch_bank, CashId FROM [@FiscalYearSource].dbo.Cheqe Cheqe WITH (NOLOCK)
    INNER JOIN Headc WITH (NOLOCK) ON Headc.Id = Cheqe.CashId
	WHERE Cheqe.CashId NOT IN(SELECT CashId FROM [@FiscalYearDestination].dbo.Cheqe WITH (NOLOCK) WHERE CashId IS NOT null);
	
	Declare @MaxRow BIGINT = (SELECT IsNull( MAX(AutoId),0) + 100 From [@FiscalYearDestination].dbo.Havaleh Havaleh)
	DBCC CHECKIDENT(TmpHavaleh, RESEED, @MaxRow);

	INSERT INTO dbo.Sanad(Id_Sanad, Type, Acc_Code,NOTE, RADIF, BEDEH, BESTAN, Edit_FLag, Auto_Create, User_ID, Tarikh, Nu_Cooperative,  FactorId,  IncrementalDeductionId, CashId)
	SELECT Heads.Id_Sanad, type, Acc_Code,##DocumentFactor.NOTE, RADIF, BEDEH, BESTAN, Edit_FLag, Auto_Create, ##DocumentFactor.User_ID, ##DocumentFactor.Tarikh,  Nu_Cooperative,  FactorId,  IncrementalDeductionId, CashId FROM dbo.HeadS
	INNER JOIN ##DocumentFactor ON CONVERT(VARCHAR(10),##DocumentFactor.FactorDate,111) = CONVERT(VARCHAR(10),Heads.Tarikh_User,111)
	WHERE Auto = 1 And FactorId NOT IN(SELECT FactorId FROM [@FiscalYearDestination].dbo.Sanad WITH (NOLOCK) WHERE FactorId IS NOT null);

	INSERT INTO dbo.Sanad(Id_Sanad, Type, Acc_Code,NOTE, RADIF, BEDEH, BESTAN, Edit_FLag, Auto_Create, User_ID, Tarikh, Nu_Cooperative,  FactorId,  IncrementalDeductionId, CashId)
	SELECT Heads.Id_Sanad, type, Acc_Code,##DocumentCash.NOTE, RADIF, BEDEH, BESTAN, Edit_FLag, Auto_Create, 
	##DocumentCash.User_ID, ##DocumentCash.Tarikh,  Nu_Cooperative,  FactorId,  IncrementalDeductionId, CashId FROM [@FiscalYearDestination].dbo.HeadS HeadS
	INNER JOIN ##DocumentCash ON CONVERT(VARCHAR(10),##DocumentCash.FactorDate,111) = CONVERT(VARCHAR(10),Heads.Tarikh_User,111)
	WHERE Auto = 1 And CashId NOT IN(SELECT CashId FROM [@FiscalYearDestination].dbo.Sanad WITH (NOLOCK) WHERE CashId IS NOT null);

	UPDATE Sanad SET Nu_Havaleh = Headh.Id_Havaleh FROM [@FiscalYearDestination].dbo.Sanad Sanad
	INNER JOIN [@FiscalYearDestination].dbo.headh Headh ON Headh.Id = Sanad.FactorId
	Inner join ##FactorHeader on ##FactorHeader.Id = Headh.Id
	Where IsNull(Sanad.Nu_Havaleh,0) <> IsNull(Headh.Id_Havaleh,0)

	UPDATE Sanad SET Nu_Over_Under = Over_Under_Factor.AutoId FROM [@FiscalYearDestination].dbo.Sanad Sanad
	INNER JOIN [@FiscalYearDestination].dbo.Over_Under_Factor Over_Under_Factor ON Over_Under_Factor.Id = Sanad.IncrementalDeductionId
	Inner join ##IncrementalDeduction on ##IncrementalDeduction.Id = Over_Under_Factor.Id
	Where IsNull(Nu_Over_Under,0) <> IsNull(Over_Under_Factor.AutoId,0)

	UPDATE Sanad SET Nu_Vajeh = Headc.Id_Cheqe FROM [@FiscalYearDestination].dbo.Sanad Sanad
	INNER JOIN [@FiscalYearDestination].dbo.Headc Headc ON Headc.Id = Sanad.CashId
	Inner join ##CashHeader on ##CashHeader.Id = Headc.Id
	Where IsNull(Nu_Vajeh,0) <> IsNull(Headc.Id_Cheqe,0)

	Update Headh Set Sanad = Sanad.Id_Sanad FROM [@FiscalYearDestination].dbo.Headh Headh
	INNER JOIN [@FiscalYearDestination].dbo.Sanad Sanad ON Headh.Id = Sanad.FactorId
	INNER JOIN ##FactorHeader ON ##FactorHeader.Id = Headh.Id
	WHERE IsNull(Sanad,0) <> IsNull(Sanad.Id_Sanad,0)

	UPDATE Sanad SET Note = (
							 CASE 
							   WHEN Headh.Kind_Flag = 2 THEN REPLACE(Sanad.Note, Headh.Nu_Resid, Headh.Id_Havaleh) 
							   WHEN Headh.Kind_Flag = 3 THEN REPLACE(Sanad.Note, Headh.Nu_Kharid, Headh.Id_Havaleh) 
							   WHEN Headh.Kind_Flag = 4 THEN REPLACE(Sanad.Note, Headh.Nu_Bargasht_kharid, Headh.Id_Havaleh) 
							   WHEN Headh.Kind_Flag IN(5,7,9) THEN REPLACE(Sanad.Note, Headh.Nu_Forosh, Headh.Id_Havaleh) 
							   WHEN Headh.Kind_Flag IN(6,8,0) THEN REPLACE(Sanad.Note, Headh.Nu_Bargasht_Forosh, Headh.Id_Havaleh) 
							 End
							)
	FROM [@FiscalYearDestination].dbo.Sanad Sanad WITH (NOLOCK)
	INNER JOIN [@FiscalYearDestination].dbo.Headh Headh WITH (NOLOCK) ON Headh.Id_Havaleh = Sanad.Nu_Havaleh
	INNER JOIN ##FactorHeader ON ##FactorHeader.Id = Headh.Id
	WHERE ISNULL(Headh.Sended,0) <> 1
	
	UPDATE Headh SET 
	Nu_Resid = (CASE WHEN Headh.Kind_Flag = 2 THEN Headh.Id_Havaleh END),
	Nu_Kharid = (CASE WHEN Headh.Kind_Flag = 3 THEN Headh.Id_Havaleh END),
	Nu_Bargasht_Kharid = (CASE WHEN Headh.Kind_Flag = 4 THEN Headh.Id_Havaleh END),
	Nu_Forosh = (CASE WHEN Headh.Kind_Flag IN(5,7,9) THEN Headh.Id_Havaleh END),
	Nu_bargasht_Forosh = (CASE WHEN Headh.Kind_Flag IN(6,8,0) THEN Headh.Id_Havaleh END) FROM [@FiscalYearDestination].dbo.headH Headh WITH (NOLOCK)
	INNER JOIN ##FactorHeader ON ##FactorHeader.Id = Headh.Id
	WHERE ISNULL(Headh.Sended,0) <> 1 	 

	UPDATE Headh SET Sended = 1 FROM [@FiscalYearDestination].dbo.headH Headh WITH (NOLOCK)
	INNER JOIN ##FactorHeader ON ##FactorHeader.Id = Headh.Id
	WHERE ISNULL(Headh.Sended,0) <> 1' 

SET @CreateTableErrorCommand =
'IF Not EXISTS(SELECT * FROM sysobjects WHERE name=''TransferBetweenFinancialYearsError'')
BEGIN 
	CREATE TABLE [dbo].[TransferBetweenFinancialYearsError](
	[Id] [UNIQUEIDENTIFIER] NOT NULL,
	[SqlCommand] [NVARCHAR](MAX) NOT NULL,
	[ErrorMessage] [NVARCHAR](MAX) NOT NULL,
	[CreatedOn] [DATETIME] NOT NULL,
    CONSTRAINT [PK_TransferBetweenFinancialYearsError] PRIMARY KEY CLUSTERED 
    (
	  [Id] ASC
    )
    ) ON [PRIMARY] 
    ALTER TABLE [dbo].[TransferBetweenFinancialYearsError] ADD  CONSTRAINT [DF_TransferBetweenFinancialYearsError_Id]  DEFAULT (NEWID()) FOR [Id]
	ALTER TABLE [dbo].[TransferBetweenFinancialYearsError] ADD  CONSTRAINT [DF_TransferBetweenFinancialYearsError_CreatedOn]  DEFAULT (GETDATE()) FOR [CreatedOn]
END 
Else
  Truncate Table TransferBetweenFinancialYearsError'


DECLARE @TypeSaveDocuments NVARCHAR(100)
DECLARE @Type TINYINT
DECLARE @Definition nvarchar(100);
SELECT @TypeSaveDocuments = N'SELECT @Type = Type FROM [' + @FiscalYearSource  +  '].dbo.Auto_Code Where Type = 0 '
SET @Definition = N'@Type TinyInt OUTPUT';
EXEC Sp_ExecuteSql @TypeSaveDocuments, @Definition, @Type=@Type OUTPUT;
IF @Type = 0 
BEGIN 
	--------------------------(    )----------------------------
	EXEC dbo.ExecuteCommand @CreateTableErrorCommand
	PRINT 'Create Table Error Command Success'
	--------------------------(       ǘ)----------------------------
	SELECT @TmpSql =  REPLACE(@CreateFieldCommand,'@Year',@FiscalYearSource)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Field Command Success'

	SELECT @TmpSql =  REPLACE(@CreateLinkCommand,'@Year',@FiscalYearSource)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Relation Link By Field Guid Source Success'

	SELECT @TmpSql =  REPLACE(@CacheFactorCommand,'@FiscalYearSource',@FiscalYearSource)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Cache Factor Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@UnitsCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Cache Units Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@GroupCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Group Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@IncrementalDeduction,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create IncrementalDeduction Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@GoodsCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Goods Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@RelationGoodsCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create RelationGoodsCommand Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@WarehouseCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Warehouses Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@PersonCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Persons Success'

	SELECT @TmpSql =  REPLACE(REPLACE(@BankCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Banks Success'

	-------------------------------(  Guid  )------------------------------------
	SELECT @TmpSql =  REPLACE(@CreateFieldCommand,'@Year',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Field Destination Success'

	---------------------------------(Guid     )--------------------------------------
	SELECT @TmpSql =  REPLACE(@CreateLinkCommand,'@Year',@FiscalYearSource)
	EXEC dbo.ExecuteCommand @TmpSql
	PRINT 'Create Relation Link By Field Guid Source Success'

	--------------------(        )-------------------------------
	IF OBJECT_ID('Sp_DisableTrigger') IS NULL
	EXEC(@StatusTriggersCommand)
	EXEC dbo.Sp_DisableTrigger 'Disable','Headh,Havaleh, Over_Under_Factor, Headc, Cheqe, Sanad', 'ExecIsInsertTrigger'
	EXEC dbo.Sp_DisableTrigger 'Disable','Headh,Havaleh, Over_Under_Factor, Headc, Cheqe, Sanad', 'ExecIsUpdateTrigger'
	--------------------(   Ϙ   ǘ )-------------------------------
	SELECT @TmpSql =  REPLACE(@CreateAutoAccountingDocumentCommand,'@Year',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql 
	PRINT 'Create Auto AccountingDocument Success'

	--------------------( ǘ      )--------------------------------
	SELECT @TmpSql =  REPLACE(REPLACE(@SaveFactorCommand,'@FiscalYearSource',@FiscalYearSource),'@FiscalYearDestination',@FiscalYearDestination)
	EXEC dbo.ExecuteCommand @TmpSql
	EXEC dbo.Sp_DisableTrigger 'Enable','Headh,Havaleh, Over_Under_Factor, Headc, Cheqe, Sanad', 'ExecIsInsertTrigger'
	EXEC dbo.Sp_DisableTrigger 'Enable','Headh,Havaleh, Over_Under_Factor, Headc, Cheqe, Sanad', 'ExecIsUpdateTrigger'
	PRINT 'Send Factors From FiscalYear Source Success'
END 

