While alter table adding foreign key getting error in SQL Server - sql

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.

Related

How do i add foreign key to existing table?

I am trying to add a foreign key to the table STUDENTS from the table PROGRAMS
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD FOREIGN KEY(ProgramId) REFERENCES
PROGRAMS(ProgramId);
But it giving the following error :
Foreign key 'ProgramId' references invalid column 'ProgramId' in referencing table 'STUDENTS'
Not sure what i am doing wrong here any tip or solution would be a great help.
The column needs to exist in the table before it can be used for a foreign key reference. So I assume you intend something like:
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD ProgramId INT; -- have to guess at the type
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD FOREIGN KEY (ProgramId) REFERENCES
PROGRAMS(ProgramId);
You appear to want to add a column with a related foreign key.
In SQL Server, you can do this in a single commad, like so:
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD ProgramId INTEGER
CONSTRAINT StudentsProgramIdFk FOREIGN KEY(ProgramId) REFERENCES PROGRAMS(ProgramId);
You should adjust the datatype of the column to your exact need. The key point is that the new column must have the same datatype as the column it references (that is PROGRAMS(ProgramId)).

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.

Unable to add foreign key constraint due to obscure conflict

Trying to run :
ALTER TABLE [dbo].[Table1] ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID]) ON DELETE CASCADE
Getting this error :
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_ScenarioResult". The conflict occurred in database "8362", table "dbo.ScenarioResult", column 'ScenarioResultID'.
I have checked :
Constraint does not already exist, and no other exists on same column
The values in the column match in both tables
Types of columns are the same
Tried a different name, also fails
On SQL Server 2008 R2
Any ideas what I could try?
In theory this might work:
ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID])
ON DELETE CASCADE
Not sure how you checked for integrity of existing values, but it should be:
SELECT COUNT(*) as Orphans FROM [dbo].[Table1] t
WHERE NOT EXISTS
(SELECT * FROM [dbo].[ScenarioResult] WHERE ScenarioResultID = t.ScenarioResultID)
If "Orphans" is greater then zero you need to clean the data before adding a constraint.
This one was baffling me aswell, and then the penny dropped.
I was trying to create a Foreign Key using "Database Diagrams" in SQL Server 2012, but it refused to let me as it claimed to clash with the foreign key I was trying to create. Huh ?
But, I had accepted the defaults to "Enforce foreign key constraint". But I already had data in the two tables I was attempting to create a foreign key for, and it was breaking the foreign key rule I was trying to make, so SQL Server was rejecting the new key.
The solution (in this particular case) was to change "Enforce foreign key constraint" to "No", or at least until I had cleaned up my data.
Hope this helps.
I had the same issue
I clear the data of the tables where i want to edit the content and add a new foreign key constraint and retry.
It works for me.
I hope it help you.

Error Adding Multiple FK Relationship in SQL Server 2008

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!

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.