IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DeleteFrlloRemainsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_DeleteFrlloRemainsProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_DeleteFrlloRemainsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_DeleteFrlloRemainsProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2023 11 24
-- Description: Удаление данных ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_DeleteFrlloRemainsProcess]
    @Id uniqueidentifier,
    @OnlyClean bit
AS
BEGIN

	if(exists(select 1 from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsId = @Id and [Status] = 2))
	begin
			RAISERROR('Удаление запрещенно!', 16, 10) 	
	end

	if(exists(select 1 from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = @Id and FrlloStatus <> 400 and FrlloStatus is not null))
	begin
			RAISERROR('Есть успешно принятые в ФРЛЛО данные. Удаление запрещенно!', 16, 10) 	
	end

	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO_REMAINS_DATA WHERE ExportFrlloRemains = @Id)
	BEGIN
		delete TOP(1000) from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = @Id
	END

    if(@OnlyClean = 1)
    begin 
	    update  RDS.T_EXPORT_FRLLO_REMAINS set Status = 0 where ExportFrlloRemainsID = @Id
    end
    else
	    delete from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsID = @Id

END

