I’m trying to set up a relationship in my database between the Appointments table and the Centres table.
One quirk about the system is that if there is no Centre recorded in the user’s area, it must still allow an appointment to be recorded. In this case, the linked centreid will have a 0 value.
This means that I’m getting the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint ‘fk_appointments_centres”.
The code I’m using to create the relationship follows:
alter table appointments
add constraint fk_appointments_centres
foreign key (centreid)
references centres(centreid)
on delete cascade
go
This is very important because the client wants functionality to delete centres from the system and in that case, to maintain the data properly, it should also delete a centre’s appointments if the centre is deleted.
Ideally I’d like this relationship to work, but as the centreid column on the Centres table has IDENTITY_INSERT ON, I don’t think this will work.
I can think of 2 other options, but they’re not ideal so I’d like to get this to work if possible.
Can anyone help me out?
EDIT
I just saw something on MSDN where someone recommended not verifying existing data. This seems like it could work, but how will this affect data input going forward? Reference here
I think it is not a good idea to set a FK to a record on a column which could have reference IDs which not exists! (Do you have a Centre with ID 0 to where reference?)
1: Instead of using 0 you should try using NULL instead. Because then the FK would work.
2: Create an “admin” record with a special ID like ID which could support this reference
3: In last case you can try to use a Delete trigger on that table to make it “manually”, but I do not recommand that solution.