IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_DeleteFrlloCertificate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_DeleteFrlloCertificate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2025 07 11
-- Description: Удаление данных ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_DeleteFrlloCertificate]
    @Id uniqueidentifier,
    @RemovalAllowed bit
AS
BEGIN
    if (exists (select 1 from RDS.T_FRLLO_MESSAGE where ExportFrlloElectronicCertificate = @Id))
    begin
        if (@RemovalAllowed = 1)
        begin
            delete from RDS.T_FRLLO_MESSAGE where ExportFrlloElectronicCertificate = @Id
        end
        else
        begin
            raiserror('Нельзя удалить запись, так как существуют связанные сообщения', 16, 1)
            return
        end
    end
    
	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO_EC_DATA WHERE ExportFrlloElectronicCertificate = @Id)
	BEGIN
		DELETE TOP(10000) from RDS.T_EXPORT_FRLLO_EC_DATA where ExportFrlloElectronicCertificate = @Id
	END
	
	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO_ELECTRONIC_CERTIFICATE WHERE ExportFrlloElectronicCertificateID = @Id)
	BEGIN
		DELETE TOP(10000) from RDS.T_EXPORT_FRLLO_ELECTRONIC_CERTIFICATE where ExportFrlloElectronicCertificateID = @Id
	END
END