Error Adding Multiple FK Relationship in SQL Server 2008 - sql

Consider we have two tables ProductType and ProductSizeGroup as below
ProductType
Id
Name
MaleSizeGroupId
FemaleSizeGroupId
ChildSizeGroupId
ProductSizeGroup
Id
Name
Each of MaleSizeGroupId, FemaleSizeGroupId and ChildSizeGroupId fields should be FKs to ProductSizeGroup.Id.
I add one using the following statement:
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Male] FOREIGN KEY([MaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
This works fine. I try to add the next using
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Female] FOREIGN KEY([FemaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
But I get the error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_ProductType_ProductSizeGroup_Female". The conflict
occurred in database "dbname", table "dbo.ProductSizeGroup", column
'Id'.
So there is conflict.. but what conflict? What should I be looking for?

That just means: there are rows in your table ProductType that have values in the FemaleGroupId column which do not exist in the referenced table (ProductSizeGroup).
It's not a problem per se - you can totally have multiple columns going from one table to another.
The problem is with the existing data - you have data in there that doesn't live up to that FK constraint. Fix that data and you should be fine.
To find those offending rows, use a query like this:
SELECT *
FROM [dbo].[ProductType]
WHERE FemaleGroupId NOT IN (SELECT DISTINCT Id FROM [dbo].[ProductSizeGroup])
That will list all offending rows - update their attribute and get going again!

Related

While alter table adding foreign key getting error in SQL Server

I am trying to add a foreign key in SQL Server to an existing table, but I'm getting an error. Could any one please help me?
Note: objid is present in both table 1 & table 2
ALTER TABLE table1
ADD CONSTRAINT FK_41_PRICE_INST2PRICE_QTY
FOREIGN KEY (Table1 PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
Error:
FK_40_PRICE_INST2PRICE_QTY. The conflict occurred in database "test", table "dbo.table2", column 'objid'.
Apart from the error in the syntax, I think there are some values in the objid column that doesn't exist in the PRICE_INST2PRICE_QTY table. You have to check the values between the two columns. This is why you are creating the foreign key to prevent such things.
The syntax should be something more like this:
ALTER TABLE table1
ADD CONSTRAINT FK_41_PRICE_INST2PRICE_QTY
FOREIGN KEY (PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
You don't need to qualify the column name.
Do a quick check on you column 'objid' and don't write
FOREIGN KEY (Table1 PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
It should be more like:
FOREIGN KEY (PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
without table1, because you're working in table1.

MSSQL Foreign Key Relationship and Null values

I'm having problems adding a foreign key to an existing table where the foreign key can be null.
Say I have a user table and a data table. The data table already has a working foreign key on the "createdBy" colum to the user table ID column. I've just added a second column to the data table "EditedBy" that allows for null values (meaning the data record hasn't been edited). So all the existing records have NULL as the value for this column.
I am trying to make a foreign key between Data.EditedBy and User.Id, but when I try to apply it, I get the following error.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Data_User_EditedBy". The conflict occurred in database "Test", table "dbo.User", column 'Id'.
It seems like its having a problem with the NULL values in the data table, but NULL is an acceptable value for a foreign key.
What am I missing?
UPDATE:
Full statement is as follows
USE [Test]
GO
ALTER TABLE [dbo].[Data] WITH CHECK ADD CONSTRAINT [FK_Data_User_EditedBy] FOREIGN KEY([Id])
REFERENCES [dbo].[User] ([Id])
GO
Ok, I feel like an idiot. I was using Management studio to create the relationship, and after I posted the equivalent alter statement (which didn't work either), I realized I was trying to make a foreign key between the ID field of [data] and the ID field of [user].
Obviously that wont work.
I fixed the statement to use the correct field in the [data] table and all is well.

What would be the best way to link these two tables

I have two tables in a database, both of which are derived from official government reference tables originally supplied in spreadsheet form.
The structure of these two tables are illustrated below.
Table 1 (Species Codes)
Table 2 (Allowed presentation codes)
When I try and create a relationship between the first and the second (so as to make full use of the ability to look up values in the second table I get the following error when trying to link speciescodes.FAOCode to allowedstates.ErsSpeciesCodes).
'SpeciesCodeLookup' table saved successfully
'AllowedPresentationAndStateCodesLookup' table
- Unable to create relationship 'FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup". The conflict occurred in database "FishTrackerPro", table "dbo.SpeciesCodeLookup", column 'FAOCode'.
Can anyone enlighten me as to
1) why is this error occurring
2) is there a way (by altering one or other table where such a relation might be established?
It seems you are getting this issue because referential integrity is not met. I.e Foreign key table must not have values which does not exists in primary key table.
Check these links :
Alter table conflicted with foreign key constraint
SQL conflicted with the FOREIGN KEY constraint

foreign key: conflicted with foreign key constraint

so i have 2 tables related to each other with an fk
appointment
{id, dept.id, datetime, sometable.id, sometableagain.id}
task
{id, appointment.id, deptlead.id, taskname}
deptlead
{id, name}
so i had to alter the appointment table to another foreignkey from another table. so i dropped the keys (task_appointment_fk, appointment_sometable_fk, appointment_sometableagain_fk) altered the table to add the new field and added again everything. the last two got added with no problems. while the other one (task_appointment_fk) kept giving me a this message :
"ALTER TABLE statement conflicted with the Forien Key Constraint "dept_appointment". The Cconflict occurred in the database "MyDb" , table "appointment", column "id"
so i found some solutions that states that there might be some rows on the task that has a appointmentid value that does not exist on the appointment table. so i tried inserting rows that would have the same value right. still gives me the same thing. the thing is , i want to delete the rows from the task to make it easier but doing that i have to drop all the fks again and do the same thing all over on the other tables, and i have a lot of other tables..
need some advice.
thanks!!
You can write a query to see which values in foreign key table does not have a matching key record in primary key table .If values are there then try to delete them .
select * from [task] a
left join [appointment] b
on a.appointment_id = b.id

SQL conflicted with the FOREIGN KEY constraint

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.
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
I think you have data restricted by foreign key try to check the data on both tables before assigning a foreign key, whether there are restrictions on both the tables.