简体   繁体   中英

Won't let me add a Foreign Key into a table in SQL Server

I am tidying up a database and trying to sort all the dependencies out and I keep running into an error when it comes to adding a Foreign Key into a table. I have checked for constraints and can't seem to discover any so I am just wondering where the issue lies.

'PATIENTS' table saved successfully 'Appointments' table - Unable to create relationship 'FK_Appointments_PATIENTS'. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Appointments_PATIENTS". The conflict occurred in database "OEPD_PRO", table "dbo.PATIENTS", column 'PatientNumber'.

This is the error which keeps flagging up when I try to save the table. 'PatientNumber' is the Primary Key in the 'PATIENTS' table and I'm trying to add it as a foreign key into the 'Appointments' table.

ALTER TABLE Appointments
ADD CONSTRAINT FK_PatientAppointments
FOREIGN KEY (PatientNumber) REFERENCES PATIENTS(PatientNumber);

I'm very grateful for any help/advice given.

Thanks, KB

Check Appointments for invalid PatientNumber s

select *
from Appointments a 
where not exists (
  select 1
  from Patients p
  where a.PatientNumber = p.PatientNumber
  )

If they need to be removed you can delete them like so:

delete a
from Appointments a 
where not exists (
  select 1
  from Patients p
  where a.PatientNumber = p.PatientNumber
  )

Then try adding your foreign key.

It can be because there are already data in the table that does not match the Foreign Kye values. Suppose I have the values 1,2 and 3 in the Patients.PatientId and the field Appointments.PatientId has a value 4 so that does not meet the constraint rule. So Before adding the constraint make sure that you does not have any such invalid data in the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM