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

AS
BEGIN
    if (exists (select 1 from RDS.T_FRLLO_MESSAGE where ExportFrllo = @Id))
    begin
        if (@RemovalAllowed = 1)
        begin
            delete from RDS.T_FRLLO_MESSAGE where ExportFrllo = @Id
        end
        else 
        begin
            raiserror('Нельзя удалить запись, так как существуют связанные сообщения', 16, 1)
            return
        end
    end

	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO_DATA WHERE ExportFrllo = @Id)
	BEGIN
		DELETE TOP(10000) from RDS.T_EXPORT_FRLLO_DATA where ExportFrllo = @Id
	END
	
	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO WHERE ExportFrlloID = @Id)
	BEGIN
		DELETE TOP(10000) from RDS.T_EXPORT_FRLLO where ExportFrlloID = @Id
	END
END