delete
	PG_CRED_HISTORICO_CPL
from
	PG_CRED_HISTORICO_CPL left outer join PG_FORN on
	PG_CRED_HISTORICO_CPL.cd_emp =PG_FORN.cd_emp and
	PG_CRED_HISTORICO_CPL.cd_forn = PG_FORN.cd_forn
where
	PG_FORN.cd_forn is null
go
delete 
	PG_CRED_HISTORICO
from
	PG_CRED_HISTORICO left outer join PG_CRED_HISTORICO_CPL on
	PG_CRED_HISTORICO.cd_ctr = PG_CRED_HISTORICO_CPL.cd_ctr
where 
	PG_CRED_HISTORICO_CPL.cd_ctr is null
go
IF not EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_PG_CRED_HISTORICO_CPL_PG_FORN]') AND parent_object_id = OBJECT_ID(N'[dbo].[PG_CRED_HISTORICO_CPL]'))
begin
ALTER TABLE dbo.PG_CRED_HISTORICO_CPL ADD CONSTRAINT
	FK_PG_CRED_HISTORICO_CPL_PG_FORN FOREIGN KEY
	(
	CD_EMP,
	CD_FORN
	) REFERENCES dbo.PG_FORN
	(
	CD_EMP,
	CD_FORN
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
end

