/****** Object:  StoredProcedure [dbo].[DeleteWarehouseAndRelations]    Script Date: 12/09/2022 06:53:45 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Azimi
-- Create date: 
-- Description:	
-- select * from Accwarehouse
-- =============================================
ALTER PROCEDURE [dbo].[DeleteWarehouseAndRelations] 
	@WarehouseID bigint = 0,
	@OnlyRelation bit = 0
AS
BEGIN
	SET NOCOUNT ON;
	
	BEGIN TRANSACTION
	
	DECLARE @ID as BIGINT
	SELECT @ID=FormID from AccWarehouse where FromForm = 0 and ID = @WarehouseID
	IF @ID > 0
	BEGIN
		EXEC DeleteFactorAndRelations @FactorID = @ID, @OnlyRelation =@OnlyRelation 
	END
	SELECT @ID=OutID from AccWarehouse where ID = @WarehouseID
	IF @ID > 0
	BEGIN
		EXEC DeleteWarehouseAndRelations @WarehouseID = @ID, @OnlyRelation =@OnlyRelation 
	END

	Delete AccDocItem where RelationTable=9 and RelationTableID in (select ID from AccWarehouseDetails where WarehouseID = @WarehouseID)
--؟	Delete AccDocItem where RelationTable=10 and RelationTableID = @WarehouseID

	if @OnlyRelation=0
	BEGIN
		Delete AccWarehouseDelivery where WareDetailsID in (select ID from AccWarehouseDetails where WarehouseID = @WarehouseID)
		Delete AccWarehouseDetails where WarehouseID = @WarehouseID
		Delete AccWarehouse where ID = @WarehouseID
	END
	ELSe
	BEGIN
		update AccWarehouseDetails SET DocItemID=0 WHERE WarehouseID = @WarehouseID
		update AccWarehouse SET FormID=0 where ID = @WarehouseID
		update AccWarehouse SET InOROut = InOROut+100 where ID = @WarehouseID and InOROut < 100
	END

	COMMIT

END