IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_CleanFrlloRequestProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_CleanFrlloRequestProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_CleanFrlloRequestProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_CleanFrlloRequestProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2023 09 06
-- Description: Выгрузка данных в ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_CleanFrlloRequestProcess]
    @ExportId uniqueidentifier
AS
BEGIN

DECLARE @NUM INT = 1000

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

	INSERT INTO #TMP_OBJ(ID)
	SELECT DISTINCT ExportFrlloDrugRequestItemID
	FROM RDS.T_EXPORT_FRLLO_DRUG_REQUEST_ITEM fed  
	WHERE fed.ExportFrlloDrugRequest = @ExportId

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

		UPDATE fed
			SET 
				 fed.FrlloId = NULL
				,fed.FrlloStatus = NULL
				,fed.FrlloPersNeedsId = NULL
				,fed.FrlloError = null
		FROM RDS.T_EXPORT_FRLLO_DRUG_REQUEST_ITEM fed
		WHERE EXISTS(SELECT 1 FROM #TMP_OBJ T WHERE T.ID = fed.ExportFrlloDrugRequestItemID AND T.NUM <= @NUM)
		and COALESCE(fed.FrlloStatus, 1) <> 1 and fed.ExportFrlloDrugRequest = @ExportId

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

	END
END				