/****** Object:  StoredProcedure [dbo].[DeleteFactorAndRelations]    Script Date: 28/02/2022 05:49:52 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Azimi
-- Create date: s
-- Description:	
-- =============================================
ALTER PROCEDURE [dbo].[DeleteFactorAndRelations] 
	@FactorID bigint = 0,
	@OnlyRelation bit = 0
AS
BEGIN
	SET NOCOUNT ON;
	
	BEGIN TRANSACTION

	IF CURSOR_STATUS('global','FactorCursor')>=-1
		DEALLOCATE FactorCursor

	DECLARE @ID as BIGINT
	DECLARE FactorCursor CURSOR FOR select WareOutID from AccFactor where ID = @FactorID
	Open FactorCursor
	
	FETCH NEXT FROM FactorCursor INTO @ID
	WHILE @@FETCH_STATUS = 0 
	BEGIN
		EXEC DeleteWarehouseAndRelations @WarehouseID=@ID
		FETCH NEXT FROM FactorCursor INTO @ID
	END
	CLOSE FactorCursor
	DEALLOCATE FactorCursor

	Delete AccDocItem where RelationTable=12 and RelationTableID in (select id from AccFactorDetail where FactorID = @FactorID)

	if @OnlyRelation=0
	BEGIN
		Delete AccFactorDetail where  FactorID = @FactorID
		Delete AccFactor where ID = @FactorID
	END
	ELSe
	BEGIN
		update AccFactorDetail SET DocItemID=0 WHERE FactorID = @FactorID
		update AccFactor SET WareOutID=0 where ID = @FactorID
	END

	COMMIT

END