SSMS will not let me create a PK FK relationship - sql

First, let me say that I am a newbie and that I have read many other posts with the same problem. I have a table called "AllPeople", and in that table I have an integer column called "Ethnicity", which I want to be a foreign key that points at a record in my "RefEthnicities" table. I keep getting the following message:
Unable to create relationship 'FK_AllPeople_RefEthnicities'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllPeople_RefEthnicities". The conflict occurred in database "MVC-Cemeteries-Dev", table "dbo.RefEthnicities", column 'ID'.
I set up the relationship in the "AllPeople" table and told it that the primary key is the ID column in the "RefEthnicities" and the foreign key is the "Ethnicity" column in the "AllPeople" table. What am I doing wrong? My RefEthnicities table is new; no data in it.
While in design mode I set the ID field in the "RefEthnicities" table set as primary key by clicking the small box to the left of the name "ID", and down below in this same window in the column properties tab, I told it to set the index specification to "yes".
I am sure it is something simple that I am doing but I can't figure it out.
Error Message
Constraint Folder
Setting Up PK FK Link

As my limited information in the question, there 2 possibilities
NULL or Blank '' value for column Ethnicity in table AllPeople
SELECT A.Ethnicity,A.*
FROM dbo.AllPeople A
WHERE ISNULL(A.Ethnicity,'')=''
Some values column Ethnicity in table AllPeople don't have parent in column ID in table RefEthnicities
SELECT A.Ethnicity,R.ID, *
FROM dbo.AllPeople A
LEFT JOIN RefEthnicities R
ON A.Ethnicity=R.ID
WHERE R.ID IS NULL
If you get any rows in two queries, then you need to fix data in column Ethnicity in table AllPeople.
Read

Ok this still makes no sense. If I create two brand new tables with the following:
table1
ID primary key int not nullable
value varchar
table2FK
table2
ID primary key int not nullable
value varchar
and in table1 I make a relationship between table2FK and Table2.ID, it works perfect with no data saved in the tables. If I use the exact same process in my AllPeople and RefEthnicicties tables, I get the error. This makes no sense. What am I missing?
adam

That fixed it. many thanks. I had a record in my AllPeople table for ethnicity that had a value of 0. Since I didn't have a record in the RefEthnicity Table with an ID of 0, it was telling me that I couldn't do this.
adam

Related

Bypass database constraints during record deletion

I have around 20 mapping tables which refer to a single table.
The single table being referenced is,
field (
id integer,
value char
)
The mapping tables are as,
employee_field_map (
employee_id integer references employee(id),
field_id references field(id)
)
dept_field_map (
dept_id integer references dept(id),
field_id references field(id)
)
and similar additional 18 mapping tables.
Now if I want to delete number of records from the field table where field.id = employee_field_map.field_id it takes very long amount of time because there are 20 mapping tables which refer to the field table; And for each of that mapping table a constraint violation check is performed before deleting a record from the field table.
A field table rcord will always be referenced by only one of the mapping table at a time.
In above scenario before deleting a record from field table of course the corresponding record in employee_field_map table is deleted first. So I know for sure that none of the mapping table contains a reference to the field table record being deleted. So is there a way to tell the database engine not to perform those constraint checks when the delete on field table is being performed?
Disabling the constraints is not an option unfortunately. Please advise.
Assuming each of the mapping tables has an index on field_id, then the lookups should not be expensive.
I am wondering why you are not declaring them using cascading delete foreign key references:
employee_field_map (
employee_id integer references employee(id),
field_id references field(id) on delete cascade
);
Nothing in your data model is saying that the field is in only one mapping table. In fact, I don't see why things are broken out the way they are. Presumably there is a reason for breaking the fields apart like this instead of just having a "type" column in the fields table.

There are no primary or candidate keys in the referenced table '' that match the referencing column

I have a table that has a primary key voucher_no (varchar(10)) and I am trying to create a FK to this table/column from another new table but I am getting an error:
There are no primary or candidate keys in the referenced table 'apinv_hdr' that match the referencing column list in the foreign key 'fk_invoice_cfdi_x_voucher_apinv_hdr'
I have several other FK's tied to this table/column - why would it react this way now?
Primary Key and Foreign Key data types must match. Have you verified the column data types are the same?
Looks like some voucher_no record in another new table doesn't exist in voucher_no in main table.
Below script may help you.
select *
from another_new_table
where voucher_no not in (select voucher_no
from main_table)
If above query returns rows, you have two options:
delete those records from another_new_table or
insert records into main_table

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 Server 2008: The columns in table do not match an existing primary key or unique constraint

I need to make some changes to a SQL Server 2008 database.
This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne.
However when I tried to do this (through SQL Server Management Studio) I got the following error:
The columns in table 'tblOne' do not
match an existing primary key or
UNIQUE constraint
I'm not really sure what this means, and I was wondering if there was any way around it?
It means that the primary key in tblOne hasn't been properly declared - you need to go to tblOne and add the PRIMARY KEY constraint back onto it.
If you're sure that tblOne does have a PRIMARY KEY constraint, then maybe there are multiple tblOne tables in your DB, belonging to different schemas, and your references clause in your FK constraint is picking the wrong one.
If there's a composite key (which your comment would indicate), then you have to include both columns in your foreign key reference also. Note that a table can't have multiple primary keys - but if it has a composite key, you'll see a key symbol next to each column that is part of the primary key.
If you have a composite key the order is important when creating a FK, and sometimes the order is not how it is displayed.
What I do is go to the Keys section of the table1 and select script primary key as create to clipboard and then create FK using the order as shown in script
I've had this situation that led me to this topic. Same error but another cause. Maybe it will help someone.
Table1
ColA (PK)
ColB (PK)
ColC
Table2
ID (PK)
ColA
COLB
When trying to create foreign key in Table2 I've choose values from combobox in reverse order
Table1.ColB = Table2.ColB
Table1.ColA = Table2.ColA
This was throwing me an error like in topic name. Creating FK keeping order of columns in Primary key table as they are, made error disappear.
Stupid, but.. :)
If you still get that error after you have followed all advice from the above answers and everything looks right.
One way to fix it is by Removing your Primary keys for both tables, Save, Refresh, and add them again.
Then try to add your relationship again.
This Error happened with me When I tried to add foreign key constraint starting from PrimaryKey Table
Simpy go to other table and and create this foreign key constraint from there (foreign key Table)
This issue caught me out, I was adding the relationship on the wrong table. So if you're trying to add a relationship in table A to table B, try adding the relationship in table B to table A.
That looks like you are trying to create a foreign key in tblTwo that does not match (or participate) with any primary key or unique index in tblOne.
Check this link on MSDN regarding it. Here you have another link with a practical case.
EDIT:
Answwering to your comment, I understand you mean there are 2 fields in the primary key (which makes it a composite). In SQL it is not possible to have 2 primary keys on the same table.
IMHO, a foreign key field should always refer to a single register in the referenced table (i.e. the whole primary key in your case). That means you need to put both fields of the tblOne primary key in tblTwo before creating the foreign key.
Anyway, I have investigated a bit over the Internet and it seems SQL Server 2008 (as some prior versions and other RDBMS) gives you the possibility to reference only part of the primary key as long as this part is a candidate key (Not Null and Unique) and you create an unique constraint on it.
I am not sure you can use that in your case, but check this link for more information on it.
I have found that the column names must match.
Example:
So if tblOne has id called categoryId a reference in tblTwo must also be called categoryId.
_tblname, primary key name, foreign key_
tblOne, "categoryId", none
tblTwo, "exampleId", "categoryId"
I noticed this when trying to create foreign key between 2 tables that both had the column name "id" as primary key.
If nothing helps, then this could be the reason:
Considering this case:
Table A:
Column 1 (Primary Key)
Column 2 (Primary Key)
Column 3
Column 4
Table B:
Column a (Primary Key)
Column b
Column c
when you are defining a dependency B to A, then you are forced to respect the order in which the primaries are defined.
That's mean your dependency should look like this:
Table A Table B
Column 1 Column b
Column 2 Column c
AND NOT:
Table A Table B
Column 2 Column c
Column 1 Column b
then this will lead to the error you are encountering.
I've found another way to get this error. This can also happen if you are trying to make a recursive foreign key (a foreign key to the primary key in the same table) in design view in SQL Management Studio. If you haven't yet saved the table with the primary key it will return this message. Simply save the table then it will allow you to create the foreign key.
If you have data in your tables this could be the issue.
In my case I had some data in the Account table that I loaded at 3 pm, and some data in Contact table that I loaded at 3:10 pm, so Contact table had some values that weren't in my Account table yet.
I ended up deleting these values from the contact table and then managed to add a key without any problems.
Kindly also see that there are no existing data inside the table where the primary key is defined while setting the foreign key with another table column.
this was the cause of the error in my case.
I had to take backup empty the table set the relationship and then upload the data back.
sharing my experience
Was using ms sql smss

Update primary key from table in another database

I have two identical tables in two different databases with the same data but they have different primary keys, I need to update these so they have the same key, so what I did was making sure that none of the tables had any key in common and that there were no duplicates
UPDATE db1.dbo.Table
SET db1.dbo.Table.pcol = rightPcol.pcol
FROM db1.dbo.Table
JOIN db2.dbo.Table AS rightPcol ON db1.dbo.Table.2ndIdent = db2.dbo.Table.2ndIdent
this however results in "Violation of PRIMARY KEY Constraint. Cannot insert duplicate key in object"
when adding a where clause to not update any db1 pcol value that existed in the db2 pcol it didn't update anything at all, it does look like it tries to update with the primary key in db1 instead of db2.
any and all help is greatly appreciated!
//fixed minor spelling error :)
To be honest there isn't much to say - the error message pretty much describes what is it wrong.
You are trying to update a PK Column to a value that already exists.
I would double check to make sure that
by joining on 2ndIdent you are not creating any duplicates.
there really aren't any duplicates in the tables on DB1 and
DB2
Your SQL looks fine so it must be an issue with the data.
To check for duplicates you could use something like this:
Select 2ndIndent
From Table
Group By 2ndIdent
Having Count(2ndIndent) > 1
The "pcol" is the primary key column?
You get "Violation of primary key constraint" when the primary key from "rightPcol" is duplicate with any row in table in "db1". You should select duplicatetion from the two tables and resolve the conflict (how it reselove depends on others thing, which you didn't specified).
So the first you should select the duplications:
SELECT T1.pcol
FROM db1.dbo.Table.pcol AS T1
INNER JOIN db2.dbo.Table.pcol AS T2
ON T1.pcol = T2.pcol