--DROP PROCEDURE P_DSYNC_V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV
IF OBJECT_ID('P_DSYNC_V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV') IS NOT NULL
BEGIN
	DROP PROCEDURE P_DSYNC_V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV
END

GO

-- EXECUTE P_DSYNC_V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV 8,12,0
CREATE PROCEDURE P_DSYNC_V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV @CLIENT_ID INT,@CD_FILIAL INT = NULL,@TP_ALTERACAO INT = 0
AS
BEGIN

DECLARE @LAST_VERSION BIGINT
SET @LAST_VERSION = DBO.UDF_DSYNC_GET_VERSION(@CLIENT_ID,'EST_PROD_TBL_DESC_EST_PROD')


CREATE TABLE #RS_ALTERACOES (
	
	SYS_CHANGE_OPERATION CHAR,
	CD_EMP INT,
	CD_TBL_DESC INT,
	CD_PROD INT

)

--PRINT 'LAST_VERSION = ' + CAST(@LAST_VERSION AS VARCHAR)

INSERT INTO #RS_ALTERACOES
(SYS_CHANGE_OPERATION,CD_EMP,CD_TBL_DESC,CD_PROD)
SELECT
SYS_CHANGE_OPERATION,CD_EMP,CD_TBL_DESC,CD_PROD
FROM 
CHANGETABLE(CHANGES EST_PROD_TBL_DESC_EST_PROD,@LAST_VERSION) C

IF @TP_ALTERACAO = 0
BEGIN
	SELECT 
	*  
	FROM 
	#RS_ALTERACOES FILA
	INNER JOIN V_EST_PROD_TBL_DESC_EST_PROD_CARGA_PDV TABELA ON   
	FILA.CD_EMP = TABELA.CD_EMP AND 
	FILA.CD_TBL_DESC = TABELA.CD_TBL_DESC AND 
	FILA.CD_PROD = TABELA.CD_PROD
	WHERE
	TABELA.CD_FILIAL = @CD_FILIAL
END
ELSE
BEGIN
	SELECT
	*
	FROM
	#RS_ALTERACOES FILA
	WHERE
	SYS_CHANGE_OPERATION = 'D'
END

DROP TABLE #RS_ALTERACOES

END
