views:

118

answers:

1

I am trying to run some update scripts on my database and I am getting the following error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_UPSELL_DT_AMRNO_AFMKTG_REF". The conflict occurred in database "ECOMVER", table "dbo.AFFILIATE_MKTG_REF", column 'AMRNO'.

I am running the following script:

ALTER TABLE [dbo].[UPSELL_DATA]  WITH CHECK ADD 
        CONSTRAINT [FK_UPSELL_DT_AMRNO_AFMKTG_REF] FOREIGN KEY
        (
          [AMRNO]
        ) REFERENCES [dbo].[AFFILIATE_MKTG_REF] (
          [AMRNO]
        )
GO

AMRNO is a PK in table AFFILIATE_MKTG_REF.

Also, I tried to create the foreign key relation using the modify table option in SQL Management studio and I got the same error. I am not sure what I should be looking for?

Any suggestions would be greatly appreciated.

Thanks, Brennan

+7  A: 

You probably have records in your [dbo].[UPSELL_DATA] table with values in the [AMRNO] column that don't exist in the [dbo].[AFFILIATE_MKTG_REF] table, [AMRNO] column. Try a query like this to find those that don't have matching records:

select   *
from     [dbo].[UPSELL_DATA] u
left join [dbo].[AFFILIATE_MKTG_REF] m
on       u.AMRNO = m.AMRNO
where    m.AMRNO is null
chadhoc
Hello Chad,Thanks for the response. Yes, there are three records that return from your query. Do these records need to be removed before I create the FK?
Brennan Mann
Well, if you want to create a trusted constraint, you'll have to either delete them from the UPSELL_DATA table, or create associated entries in the AFFILIATE_MKTG_REF table for the given IDs. The only other option would be to keep/create an un-trusted constraint as discussed in the link above (and here http://www.mssqltips.com/tip.asp?tip=1539).
chadhoc