/****** Object:  StoredProcedure [dbo].[DeleteFactorAndRelations]    Script Date: 04/09/2021 10:42:00 ق.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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


	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)
	Delete AccFactorDetail where  FactorID = @FactorID
	Delete AccFactor where ID = @FactorID

	COMMIT

END
