Greetings!
I have inserted data from sql insert files into an ms sql database. Apperantly this data is not fully complete.
I discovered this when I was trying to make the ERD and create key constraints between tables.
When I try to connect article_review with order1 where order1 has a primary key and article review has a foreign key.
I have a query where it selects all records with non-matching key values:
see image: http://imgur.com/vDbCuG8
So what I want to do now:
insert new rows into article_review with the missing ID values. The values of the other columns do not really matter, they can be NULL or random generated.
A simple join won't really cut it because all of the other columns are non-identical.
ps. all above is needed because ms sql 2016 wont let me create a key constraint between 2 tables where one of them contains a value that is not in the other one and thus throws the error:
'order1' table saved successfully
'article_review' table saved successfully
'review' table
- Unable to create relationship 'FK_review_order1'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_review_order1". The conflict occurred in database "superDatabase", table "dbo.order1", column 'id'.
Do you just want to add the Foreign key for documentation only?
You could add the FK like this:
ALTER TABLE dbo.order1 WITH NOCHECK
ADD CONSTRAINT FK_review_order1 FOREIGN KEY (id) REFERENCES dbo.article_review (id)
note the WITH NOCHECK
This way the foreign key is created, but is not trusted and disabled, which can be seen with this query:
SELECT SCHEMA_NAME(fk.schema_id) AS sch, T.name,
fk.name, is_disabled, is_not_trusted, fk.is_not_for_replication
FROM sys.foreign_keys fk WITH (NOLOCK)
INNER JOIN sys.tables T WITH (NOLOCK) ON T.object_id = fk.parent_object_id
WHERE fk.is_not_trusted = 1
AND fk.is_disabled = 0
ORDER BY SCHEMA_NAME(fk.schema_id), T.name, fk.name;
idea from https://www.brentozar.com/blitz/foreign-key-trusted/
Related
I Not able to add foreign key to tbl1 referencing tbl2 (Desc), here are the two tables :
please notice Tbl1 includes all values,tbl2 Has more values that doesn't necessarily exists in tbl1
Error(Msg 1776): There are no primary or candidate keys in the referenced table 'tbl2' that match the referencing column list in the foreign key 'fk_desc'.
tbl1:
alter table tbl1 add constraint pk_desc primary key (desc)
The Error:**alter table tbl1 add constraint fk_desc foreign key (desc)
references tbl2(desc)**
Desc
Astrogator
Geologist
Technician
tbl2:
alter table tbl2 add constraint pk_canid_desc primary
key(id,desc)
ID
Desc
1001
Astrogator
1001
Geologist
1001
Technician
2003
Biochemist
thank you for the help,
you cant make Desc that at table tbl2 as a FK while it contains values not exists at the table tbl1
Adding a foreign key is different depending on the flavor of SQL your using. For sql server you would bring up the parent db in SSMS using table design. Select Foreign key relationships and add a new relationship. From there select other table and column which has foreign key. Keep in mind that there needs to exist a foreign key for each Primary record or you will get an error.
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.
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!
I am using SQL Server, and I need to add a foreign key to an already existing table.
The issue is the column which will act as the foreign key already has a few inconsistent values (which do not occur as a primary key) in another table.
I was wondering, when I alter the table and add the foreign key constraint, what will happen to the rows in the table with foreign key constraint , which has inconsistent values??
--Neeraj
In this case it is your decision. You can leave this values in table using WITH NOCHECK clause. But all new inserted values will be checked.
You'll get an error and nothing will be inserted.
To find all inconsistent rows (supposing that A and B are the target tables, A.id is a parent key and B.fk_id is a child, foreign key, id):
SELECT B.fk_id
FROM B
LEFT JOIN A ON A.id = B.fk_id
WHERE A.id IS NULL
After executing it you'll have all child rows that refers to "nowhere". So you either need to remove them, modify to point to the existing rows or set B.fk_id to NULL (if there is no NOT NULL constraint).
And after that query returns 0 rows - you can safely create foreign key constraint without any magic options.
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.