IF EXISTS (
		SELECT *
		FROM sys.objects
		WHERE object_id = OBJECT_ID(N'[dbo].[P_LOJA_NOVA_PRECOS]')
			AND type IN (N'P', N'PC')
		)
	DROP PROCEDURE [dbo].[P_LOJA_NOVA_PRECOS]
GO

--EXEC P_LOJA_NOVA_PRECOS  1,35
--Procedure para replicar cadastro de preços
CREATE PROCEDURE [dbo].[P_LOJA_NOVA_PRECOS] (
	@IN_CD_FILIAL_BASE INT = 1
	,@IN_CD_FILIAL_DESTINO INT = 1
	)
AS
SET DEADLOCK_PRIORITY HIGH;
SET NOCOUNT ON;

--Replicando preços
ALTER TABLE dbo.EST_PROD_PRECO DISABLE CHANGE_TRACKING;

INSERT INTO EST_PROD_PRECO (
	CD_EMP
	,CD_FILIAL
	,CD_CTR
	,CD_PROD
	,VLR_TABELA
	,VLR_OFERTA
	,DT_CAD
	,CD_USU
	,STS_PRECO
	,VLR_CUSTO
	,PERC_ICMS
	,PERC_IMP
	,PERC_COMIS
	,PERC_DESP
	,PERC_MARGEM
	,STS_IMP_ETQ_GOND
	,VLR_TABELA_ANT
	,VLR_OFERTA_ANT
	,VLR_CUSTO_GER
	)
SELECT P.CD_EMP
	,@IN_CD_FILIAL_DESTINO AS CD_FILIAL
	,P.CD_CTR
	,P.CD_PROD
	,P.VLR_TABELA
	,P.VLR_OFERTA
	,P.DT_CAD
	,P.CD_USU
	,P.STS_PRECO
	,P.VLR_CUSTO
	,P.PERC_ICMS
	,P.PERC_IMP
	,P.PERC_COMIS
	,P.PERC_DESP
	,P.PERC_MARGEM
	,P.STS_IMP_ETQ_GOND
	,P.VLR_TABELA_ANT
	,P.VLR_OFERTA_ANT
	,0 VLR_CUSTO_GER
FROM EST_PROD_PRECO P WITH (NOLOCK)
LEFT OUTER JOIN EST_PROD_PRECO PRECO WITH (NOLOCK) ON P.CD_EMP = PRECO.CD_EMP
	AND @IN_CD_FILIAL_DESTINO = PRECO.CD_FILIAL
	AND P.CD_PROD = PRECO.CD_PROD
WHERE P.CD_EMP = 1
	AND P.CD_FILIAL = @IN_CD_FILIAL_BASE
	AND PRECO.CD_PROD IS NULL;

ALTER TABLE DBO.EST_PROD_PRECO ENABLE CHANGE_TRACKING
	WITH (TRACK_COLUMNS_UPDATED = ON);
