CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_PRECO_GRUPO_LISTA] ON [dbo].[EST_NF_ENT_IT] 
FOR INSERT
AS
DECLARE @CD_EMP					AS INT
DECLARE @CD_FILIAL				AS INT
DECLARE @CD_PROD				AS INT
DECLARE @CD_GRUPO_LISTA			AS INT
DECLARE @CD_NF					AS INT
DECLARE @VLR_CUSTO				AS MONEY
DECLARE @VLR_IT					AS MONEY
DECLARE @VLR_ICMS_IT			AS MONEY
DECLARE @VLR_DESC_IT			AS MONEY
DECLARE @PERC_ICMS				AS MONEY
DECLARE @PERC_IVA				AS MONEY
DECLARE @VLR_ICMS_SUBST_IT		AS MONEY

SET @CD_EMP=0
SET @CD_FILIAL=0
SET @CD_PROD=0
SET @CD_GRUPO_LISTA=0
SET @CD_NF=0
SET @VLR_CUSTO=0
SET @VLR_IT=0
SET @VLR_ICMS_IT=0
SET @VLR_DESC_IT=0
SET @PERC_ICMS=0
SET @PERC_IVA=0
SET @VLR_ICMS_SUBST_IT=0

SELECT		
	@CD_EMP=i.CD_EMP,
	@CD_FILIAL=i.CD_FILIAL,
	@CD_PROD=i.CD_PROD ,
	@CD_GRUPO_LISTA = g.CD_GRUPO_LISTA ,
	@CD_NF=i.CD_NF ,
	@VLR_CUSTO=i.VLR_PRC_CUSTO,
	@VLR_IT=i.VLR_IT,
	@VLR_ICMS_IT=i.VLR_ICMS_IT,
	@VLR_DESC_IT=i.VLR_DESC,
	@PERC_ICMS=i.ALIQ_ICMS,
	@PERC_IVA=i.PERC_IVA,
	@VLR_ICMS_SUBST_IT=i.VLR_ICMS_SUBS 
FROM         
	EST_PROD_PRECIFICACAO_GRUPO_PRECO_LISTA_PRC_FILIAL g INNER JOIN INSERTED i ON 
	g.CD_EMP = i.CD_EMP AND
	g.CD_FILIAL = i.CD_FILIAL 
	INNER JOIN EST_NF_ENT e ON
	e.CD_EMP = i.CD_EMP AND
	e.CD_FILIAL = i.CD_FILIAL AND
	e.CD_NF = i.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	e.CD_NT_MOV = m.CD_MOV_OP 
WHERE
	m.TP_MOV_OP_TRANSA = 0
	AND m.TP_MOV = 0	

IF @CD_GRUPO_LISTA > 0
	begin 		
		--deletando registro caso exista
		DELETE 
			e
		FROM  
			EST_PROD_PRECIFICACAO_GRUPO_PRECO_LISTA_EST_PROD e
		WHERE
			e.CD_EMP = @CD_EMP
			AND e.CD_GRUPO_LISTA = @CD_GRUPO_LISTA
			AND e.CD_PROD = @CD_PROD

		INSERT INTO EST_PROD_PRECIFICACAO_GRUPO_PRECO_LISTA_EST_PROD
		SELECT		
			@CD_GRUPO_LISTA,
			@CD_EMP,
			@CD_PROD,
			@VLR_CUSTO,
			@CD_FILIAL,		
			@CD_NF,
			@VLR_IT,
			@VLR_ICMS_IT,
			@VLR_DESC_IT,
			@PERC_ICMS,
			@PERC_IVA,
			@VLR_ICMS_SUBST_IT
	end