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

GO
CREATE PROCEDURE P_EST_PROD_DETE_IT_CORRIGIR_CUSTO_ZERADO AS
CREATE TABLE #RSPROD (CD_EMP INT, CD_LOTE INT, CD_PROD INT, VLR_CUSTO MONEY)

INSERT INTO #RSPROD
SELECT
	V_EST_PROD_DETER.CD_EMP,
	V_EST_PROD_DETER.CD_LOTE,
	V_EST_PROD_DETER.CD_PROD,
	EST_PROD_CPL.VLR_CUSTO_MD
FROM
	V_EST_PROD_DETER INNER JOIN EST_PROD_CPL ON
	V_EST_PROD_DETER.CD_EMP = EST_PROD_CPL.CD_EMP AND
	V_EST_PROD_DETER.CD_FILIAL = EST_PROD_CPL.CD_FILIAL AND
	V_EST_PROD_DETER.CD_PROD = EST_PROD_CPL.CD_PROD
WHERE
	V_EST_PROD_DETER.VLR_CUSTO = 0 

UPDATE
	EST_PROD_DETE_IT
SET 
	EST_PROD_DETE_IT.VLR_CUSTO_PROD = R.VLR_CUSTO
FROM
	#RSPROD R INNER JOIN EST_PROD_DETE_IT ON
	R.CD_EMP = EST_PROD_DETE_IT.CD_EMP AND
	R.CD_LOTE = EST_PROD_DETE_IT.CD_LOTE AND
	R.CD_PROD = EST_PROD_DETE_IT.CD_PROD 

DROP TABLE #RSPROD