IF NOT EXISTS(SELECT * FROM SYS.COLUMNS WHERE NAME = 'CD_APRES'
          AND OBJECT_ID = OBJECT_ID('EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC'))
    BEGIN
	   ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC
	   ADD CD_APRES INT NOT NULL
					   CONSTRAINT DF_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC_CD_APRES DEFAULT 0;
    END;
GO
IF NOT EXISTS(SELECT * FROM SYS.FOREIGN_KEYS 
			 WHERE NAME = 'FK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC_EST_ARV_MERC_APRESENTACAO')
    BEGIN
        UPDATE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC
        SET CD_APRES = ( SELECT MIN(CD_APRES) FROM 
				    EST_ARV_MERC_APRESENTACAO );
    END;
GO


IF NOT EXISTS(SELECT * FROM SYS.FOREIGN_KEYS
			 WHERE NAME = 'FK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC_EST_ARV_MERC_APRESENTACAO')
    BEGIN
        ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC
        ADD CONSTRAINT FK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC_EST_ARV_MERC_APRESENTACAO 
		  FOREIGN KEY(CD_EMP, CD_APRES) REFERENCES EST_ARV_MERC_APRESENTACAO(CD_EMP,CD_APRES);
    END;

GO

if exists(select * 
		  From sys.change_tracking_tables
			 where object_id= object_id('EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC'))
begin
    ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC DISABLE CHANGE_TRACKING;
end
go

IF ((SELECT count(*)  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
		  WHERE CONSTRAINT_NAME ='PK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC')=3)
BEGIN
    ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC 
	   DROP CONSTRAINT PK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC;
end
go
IF not exists (SELECT *FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
				WHERE CONSTRAINT_NAME ='PK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC')
BEGIN
    ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC
    ADD CONSTRAINT PK_EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC 
	   PRIMARY KEY(CD_EMP ASC, CD_ARV_MERC_EQUI ASC, CD_FABRIC ASC, CD_APRES ASC);

    ALTER TABLE EST_ARV_MERC_EQUIVALENTE_EST_PROD_FABRIC ENABLE CHANGE_TRACKING;

end
go

