IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_CleanFrlloNeedsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_CleanFrlloNeedsProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2025 09 11
-- Description: Отчистка выгрузки данных прогнозируемой потребности в ФРЛЛО 
-- =============================================
CREATE PROCEDURE [rds].[sp_CleanFrlloNeedsProcess]
    @ExportId int,
    @All bit
AS
BEGIN
DECLARE @NUM INT = 1000

CREATE TABLE #TMP_OBJ(
	 ID int NOT NULL UNIQUE
	,NUM INT IDENTITY(1,1)
)

	INSERT INTO #TMP_OBJ(ID)
	SELECT DISTINCT ExportFrlloNeedsElementID
	FROM RDS.T_EXPORT_FRLLO_NEEDS_ELEMENT fed  
	WHERE fed.ExportFrlloNeeds = @ExportId

WHILE EXISTS(SELECT TOP 1 1 FROM #TMP_OBJ)
	BEGIN

		UPDATE fed
			SET 
				 --frd.frlloid     = NULL,
                 fed.frllostatus = NULL,
                 fed.frlloerror  = NULL
                 --frd.Recipe_id = null,
                 --frd.Recipe_release_id = null
		FROM RDS.T_EXPORT_FRLLO_NEEDS_ELEMENT fed
		WHERE EXISTS(SELECT 1 FROM #TMP_OBJ T WHERE T.ID = fed.ExportFrlloNeedsElementID AND T.NUM <= @NUM)
        and fed.ExportFrlloNeeds = @ExportId

		DELETE #TMP_OBJ
		WHERE NUM <= @NUM
		
		SET @NUM = @NUM + 1000

	END
END					