DELETE
	PG_DESP_RAT_PG_CRED
FROM
	PG_DESP_RAT_PG_CRED LEFT OUTER JOIN PG_CRED ON
	PG_DESP_RAT_PG_CRED.CD_EMP = PG_CRED.CD_EMP AND
	PG_DESP_RAT_PG_CRED.CD_FILIAL = PG_CRED.CD_FILIAL AND
	PG_DESP_RAT_PG_CRED.NR_DP = PG_CRED.NR_DP AND
	PG_DESP_RAT_PG_CRED.ANO = PG_CRED.ANO 
WHERE
	PG_DESP_RAT_PG_CRED.CD_EMP =1
	AND PG_CRED.ANO  IS NULL

DELETE
	PG_CRED_EST_NF_ENT
FROM
	PG_CRED_EST_NF_ENT LEFT OUTER JOIN PG_CRED ON
	PG_CRED_EST_NF_ENT.CD_EMP = PG_CRED.CD_EMP AND
	PG_CRED_EST_NF_ENT.CD_FILIAL = PG_CRED.CD_FILIAL AND
	PG_CRED_EST_NF_ENT.NR_DP = PG_CRED.NR_DP AND
	PG_CRED_EST_NF_ENT.ANO = PG_CRED.ANO 
WHERE
	PG_CRED_EST_NF_ENT.CD_EMP =1
	AND PG_CRED.ANO  IS NULL

DELETE
	PG_CRED_DUP_NR_CTR
FROM
	PG_CRED_DUP_NR_CTR LEFT OUTER JOIN PG_CRED ON
	PG_CRED_DUP_NR_CTR.CD_EMP = PG_CRED.CD_EMP AND
	PG_CRED_DUP_NR_CTR.CD_FILIAL = PG_CRED.CD_FILIAL AND
	PG_CRED_DUP_NR_CTR.NR_DP = PG_CRED.NR_DP AND
	PG_CRED_DUP_NR_CTR.ANO = PG_CRED.ANO 
WHERE
	PG_CRED_DUP_NR_CTR.CD_EMP =1
	AND PG_CRED.ANO  IS NULL


CREATE TABLE #RSNOTA (CD_EMP INT,
					  CD_FILIAL INT,
					  CD_NF INT)

INSERT INTO #RSNOTA
SELECT
	CD_EMP,
	CD_FILIAL,
	CD_NF
FROM
	PG_CRED_EST_NF_ENT
GROUP BY
	CD_EMP,
	CD_FILIAL,
	CD_NF
HAVING 
	COUNT(*) > 1

DELETE
	E
FROM
	#RSNOTA D INNER JOIN PG_CRED_EST_NF_ENT E ON
	D.CD_EMP = E.CD_EMP AND
	D.CD_FILIAL = E.CD_FILIAL AND
	D.CD_NF = E.CD_NF 

DROP TABLE #RSNOTA

IF EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IX_PG_CRED_EST_NF_ENT')
BEGIN 
ALTER TABLE PG_CRED_EST_NF_ENT DROP CONSTRAINT IX_PG_CRED_EST_NF_ENT
END

ALTER TABLE DBO.PG_CRED_EST_NF_ENT ADD CONSTRAINT
	IX_PG_CRED_EST_NF_ENT UNIQUE NONCLUSTERED 
	(
	CD_EMP,
	CD_FILIAL,
	CD_NF
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]