IF EXISTS (SELECT * FROM SYS.procedures WHERE NAME = 'P_ATUALIZA_PRZ_DESC_FINAN_ITEM') 
	DROP PROCEDURE P_ATUALIZA_PRZ_DESC_FINAN_ITEM

GO
GO
CREATE PROCEDURE [dbo].[P_ATUALIZA_PRZ_DESC_FINAN_ITEM] AS
SET NOCOUNT ON;


DECLARE @CD_FILIAL INT
DECLARE @CD_NF INT
DECLARE @CD_PROD INT
CREATE TABLE #AUX_UPDATE (
	CD_FILIAL INT,
	CD_NF INT,
	CD_PROD INT,
	INF_ADIC_PROD VARCHAR (5000)
)

DECLARE _CURSOR CURSOR FOR
SELECT
	IT.CD_FILIAL,
	IT.CD_NF,
	IT.CD_PROD
FROM
	EST_NF_ENT_IT IT
	INNER JOIN EST_NF_ENT E ON
		E.CD_EMP = IT.CD_EMP
		AND E.CD_FILIAL = IT.CD_FILIAL
		AND E.CD_NF = IT.CD_NF
	INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT VINC ON
		IT.CD_EMP = VINC.CD_EMP
		AND IT.CD_FILIAL = VINC.CD_FILIAL
		AND IT.CD_NF = VINC.CD_NF
WHERE
	PRZ_DESC_FIN IS NULL
	AND E.DT_ENT >= GETDATE() - 3

OPEN _CURSOR

FETCH NEXT FROM _CURSOR INTO @CD_FILIAL, @CD_NF, @CD_PROD

WHILE @@FETCH_STATUS <> -1
BEGIN
	
	INSERT INTO #AUX_UPDATE
	SELECT IT.CD_FILIAL, IT.CD_NF, IT.CD_PROD, dbo.F_LIMPA_NUMEROS(INF_ADIC_PROD)
	FROM
		EST_NF_ENT_IT IT
		INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT VINC ON
			IT.CD_EMP = VINC.CD_EMP
			AND IT.CD_FILIAL = VINC.CD_FILIAL
			AND IT.CD_NF = VINC.CD_NF
		INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS ON
			VINC.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
			AND IT.CD_PROD = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_PROD
	WHERE
		IT.CD_EMP = 1
		AND IT.CD_FILIAL = @CD_FILIAL
		AND IT.CD_NF = @CD_NF
		AND IT.CD_PROD = @CD_PROD

	UPDATE 
		IT
	SET
		PRZ_DESC_FIN = CASE WHEN CHARINDEX('Prz:',A.INF_ADIC_PROD) > 0 THEN CONVERT(INT,SUBSTRING(ISNULL(A.INF_ADIC_PROD,'0'),CHARINDEX('Prz:',A.INF_ADIC_PROD) + 4, 3)) ELSE 0 END
	FROM
		EST_NF_ENT_IT IT
		INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT VINC ON
			IT.CD_EMP = VINC.CD_EMP
			AND IT.CD_FILIAL = VINC.CD_FILIAL
			AND IT.CD_NF = VINC.CD_NF
		INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS ON
			VINC.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
			AND IT.CD_PROD = EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_PROD
		INNER JOIN #AUX_UPDATE A ON IT.CD_FILIAL = A.CD_FILIAL 
									AND IT.CD_NF = A.CD_NF 
									AND IT.CD_PROD = A.CD_PROD
	WHERE
		IT.CD_EMP = 1
		AND IT.CD_FILIAL = @CD_FILIAL
		AND IT.CD_NF = @CD_NF
		AND IT.CD_PROD = @CD_PROD


	FETCH NEXT FROM _CURSOR INTO @CD_FILIAL, @CD_NF, @CD_PROD;
END

DROP TABLE #AUX_UPDATE;
CLOSE _CURSOR;
DEALLOCATE _CURSOR;
