IF NOT EXISTS (SELECT * FROM sys.change_tracking_tables WHERE OBJECT_ID = OBJECT_ID('EST_PROD_TBL_DESC_RC_CLI'))
	ALTER TABLE EST_PROD_TBL_DESC_RC_CLI ENABLE CHANGE_TRACKING

GO

IF EXISTS (SELECT * FROM SYS.PROCEDURES WHERE NAME = 'P_DSYNC_EST_PROD_TBL_DESC_RC_CLI_EST_PROD_TBL_DESC_RC_CLI')
	DROP PROCEDURE P_DSYNC_EST_PROD_TBL_DESC_RC_CLI_EST_PROD_TBL_DESC_RC_CLI


GO

CREATE PROCEDURE [dbo].[P_DSYNC_EST_PROD_TBL_DESC_RC_CLI_EST_PROD_TBL_DESC_RC_CLI] @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_RC_CLI')



IF @TP_ALTERACAO = 0
BEGIN

	SELECT
		C.CD_EMP, 
		C.CD_TBL_DESC,
		0 AS CD_FILIAL
	INTO 
		#RS_ALTERACOES
	FROM 
		CHANGETABLE(CHANGES EST_PROD_TBL_DESC_RC_CLI, @LAST_VERSION) C
	WHERE 
		CD_EMP = 1 

	SELECT 
		TABELA.*  
	FROM 
		#RS_ALTERACOES FILA
		INNER JOIN EST_PROD_TBL_DESC_RC_CLI TABELA 	ON   
			FILA.CD_EMP = TABELA.CD_EMP 
			AND FILA.CD_TBL_DESC = TABELA.CD_TBL_DESC 
	WHERE
		TABELA.CD_EMP = 1 

	DROP TABLE #RS_ALTERACOES
        
END


/* ALTERACOES DO TIPO DELETE */
ELSE IF @TP_ALTERACAO = 1
BEGIN

	SELECT	
		C.CD_EMP, 
		C.CD_TBL_DESC, 
		0 AS CD_FILIAL,
		SYS_CHANGE_OPERATION
	FROM 
		CHANGETABLE(CHANGES EST_PROD_TBL_DESC_RC_CLI, @LAST_VERSION) C
	WHERE
	SYS_CHANGE_OPERATION = 'D'
	AND CD_EMP = 1
END



ELSE IF @TP_ALTERACAO = 2
BEGIN
	SELECT 
		*
	FROM 
		EST_PROD_TBL_DESC_RC_CLI 
	WHERE 
		CD_EMP = 1
END

END
GO


