IF NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE NAME = 'CD_PG_CRED' AND OBJECT_ID = OBJECT_ID('PG_CRED_CONC_DDA'))
BEGIN	
ALTER TABLE dbo.PG_CRED_CONC_DDA ADD
	CD_PG_CRED int NOT NULL CONSTRAINT DF_PG_CRED_CONC_DDA_CD_PG_CRED DEFAULT 0
END

go
UPDATE
	PG_CRED_CONC_DDA
SET 
	PG_CRED_CONC_DDA.CD_PG_CRED = PG_CRED.CD_PG_CRED
FROM
PG_CRED INNER JOIN PG_CRED_CONC_DDA ON
PG_CRED.CD_EMP = PG_CRED_CONC_DDA.CD_EMP AND
PG_CRED.CD_FILIAL = PG_CRED_CONC_DDA.CD_FILIAL AND
PG_CRED.CD_CTR = PG_CRED_CONC_DDA.CD_CTR 

DELETE
FROM
	PG_CRED_CONC_DDA
WHERE
	CD_PG_CRED = 0

/****** Object:  Index [PK_PG_CRED_CONC_DDA_1]    Script Date: 17/10/2016 19:47:36 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PG_CRED_CONC_DDA]') AND name = N'PK_PG_CRED_CONC_DDA_1')
BEGIN
	ALTER TABLE [dbo].[PG_CRED_CONC_DDA] DROP CONSTRAINT [PK_PG_CRED_CONC_DDA_1]
END


/****** Object:  Index [PK_PG_CRED_CONC_DDA]    Script Date: 17/10/2016 19:47:36 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PG_CRED_CONC_DDA]') AND name = N'PK_PG_CRED_CONC_DDA')
BEGIN
ALTER TABLE [dbo].[PG_CRED_CONC_DDA] ADD  CONSTRAINT [PK_PG_CRED_CONC_DDA] PRIMARY KEY CLUSTERED 
(
	[CD_EMP] ASC,
	[CD_FILIAL] ASC,
	[CD_PG_CRED] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
IF NOT OBJECT_ID ('FK_PG_CRED_CONC_DDA_PG_CRED') IS NULL
	BEGIN
		ALTER TABLE [dbo].[PG_CRED_CONC_DDA]  DROP CONSTRAINT [FK_PG_CRED_CONC_DDA_PG_CRED] 
	END

ALTER TABLE dbo.PG_CRED_CONC_DDA ADD CONSTRAINT
	FK_PG_CRED_CONC_DDA_PG_CRED FOREIGN KEY
	(
	CD_EMP,
	CD_FILIAL,
	CD_PG_CRED
	) REFERENCES dbo.PG_CRED
	(
	CD_EMP,
	CD_FILIAL,
	CD_PG_CRED
	) ON UPDATE  NO ACTION 
		ON DELETE  NO ACTION 

