/****** Object:  StoredProcedure [dbo].[P_DSYNC_V_EST_PROD_CD_BARRA_TEMP_EST_PROD_CD_BARRA_TEMP]    Script Date: 12/16/2013 10:52:22 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_DSYNC_V_EST_PROD_CD_BARRA_TEMP_EST_PROD_CD_BARRA_TEMP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_DSYNC_V_EST_PROD_CD_BARRA_TEMP_EST_PROD_CD_BARRA_TEMP]
GO
GO
CREATE PROCEDURE [dbo].[P_DSYNC_V_EST_PROD_CD_BARRA_TEMP_EST_PROD_CD_BARRA_TEMP] @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_CD_BARRA')

/*PRINT 'LAST_VERSION = ' + CAST(@LAST_VERSION AS VARCHAR)*/

SELECT	
* 
INTO	
#RS_ALTERACOES
FROM 
CHANGETABLE(CHANGES EST_PROD_CD_BARRA,@LAST_VERSION) C

/* ALTERACOES DO TIPO INSERT / UPDATE */
IF @TP_ALTERACAO = 0
BEGIN

SELECT 
*  
FROM 
#RS_ALTERACOES FILA
INNER JOIN V_EST_PROD_CD_BARRA TABELA ON   
FILA.CD_EMP = TABELA.CD_EMP and FILA.CD_PROD = TABELA.CD_PROD and FILA.CD_BARRA = TABELA.CD_BARRA
        
END

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

SELECT
*
FROM
#RS_ALTERACOES FILA
WHERE
SYS_CHANGE_OPERATION = 'D'

END

/* TODOS OS REGISTROS / CARGA TOTAL */

ELSE IF @TP_ALTERACAO = 2
BEGIN

SELECT 
* 
FROM 
V_EST_PROD_CD_BARRA

END

DROP TABLE #RS_ALTERACOES

END