how to add foreign key to Azure SQL DB Table - sql-server

I am stumped by an Add Constraint Foreign Key error I am encountering.
I just created TableA with a Primary Key on PLAN_ID. The table contains zero records. I am attemtpting to execute:
alter table TableB
add constraint FK_TASK_PLAN Foreign Key (TASK_PLAN_ID)
references TableA (PLAN_ID)
Which keeps returning
"Msg 547, Level 16, State 0, Line 5. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_TASK_PLAN". The conflict occurred in database "DT_Worklist", table "dbo.TableA", column 'PLAN_ID'.
This essentially seems to be telling me I cannot create an FK on the specified column.
What am I doing wrong which is preventing me from creating this Foreign Key? Is it OK my Parent Table is empty or does it need at least one record? What about the FK column; does it need to be Not Null or does it need to have at least 1 record?

Actually, I think I figured this out... My PARENT Table which I just created is empty while my CHILD Table which was created * populated about a week ago already has values in the FK column. So there is no way to create the PK/FK relationship when the FK already contains values.....

Related

Table with multiple relations to a single primary key

Is it possible to create multiple relations from one table, to another table?
I have a table containing purchases, each of these purchases have a origin_country and a destination_country.
I would like to have relations (as foreign keys) to a single PK on a table from these two columns from the same table.
i have tried the following queries:
alter table Purchases
add constraint FK_Purchases_OriginCountries
foreign key (FK_OriginCountryCode) references dbo.countries
go
alter table Purchases
add constraint FK_Purchases_DestinationCountries
foreign key (FK_DestinationCountryCode) references dbo.countries
go
But end up getting a conflict, I can't however find documentation that this is not possible...
[23000][547] The ALTER TABLE statement conflicted with the FOREIGN KEY
constraint "FK_Purchases_DestinationCountries". The conflict occurred
in database "Market", table "dbo.countries", column 'ID'.
Is this relationship intentionally not possible, or did i just make a mistake?
Thank you
Yes you can.
The error is not a result of trying to create two foreign keys back to a single table, that's perfectly fine. Try running this to see it work:
create table t(i int primary key);
create table u
(
j int foreign key references t(i),
k int foreign key references t(i)
);
The problem you have is that you have some data in your Purchases table where the value in the column on which you are trying to create the foreign key does not exist in the countries table's ID column.
To find them run a query like this:
select p.*
from dbo.purchases p
where not exists
(
select *
from dbo.countries
where ID = p.FK_DestinationCountryCode
)
Note that I think your column names are a little weird here, You shouldn't call a column FK_DestinationCountryCode just because it has a foreign key on it, and a "code" is not the same kind of thing as an "ID". Your purchases table's columns should probably be called DestinationCountryID and OriginCountryID.

Error insert statement conflicted with the foreign key constraint

Issue
I have to table "Account_Manager" and "Partner" and both table contains foreign Key of each other and now I want to add data and it show the error Foreign Key conflict issue.
Guide me how I can insert data into these two table.
Table 1
Table 2
Make both columns (designated as FKs) nullable. Thats only way you can make circular reference/FK

sql - update two key columns without conflict

I want to to update a column from table patient, and add a prefix before all its fields, like
update patient
set contactdetailsID = '99999'+ contactdetailsID
where patient.id = 5294
So, row with id = 5294, will have the same value in column contactdetailsID with prefix 99999.
Before | After
012345 99999012345
the issue i am facing is that patient.contactdetailsID is the foreign key for another table "contactdetails".
So i get the following error.
Msg 547, Level 16, State 0, Line 1 UPDATE statement conflicted with
COLUMN FOREIGN KEY constraint 'ContactDetails_Patient_FK1'. The
conflict occurred in database 'A', table 'ContactDetails',
column 'id'. The statement has been terminated.
(0 row(s) affected)
How can i make that change? I want to change both patient.contactdetailsID and its key Contactdetails.ID, with the same prefix in order not to lose the connection between them.
You can temporary disable the Foreign-Key Constraint using:
ALTER TABLE *Tablename*
NOCHECK CONSTRAINT *ForeinKey_Name*;
and update both the ContactDetails Table and Patient Table.
But make sure that you enable the ForeignKey afterwards!
To enable a Foreign Key use
ALTER TABLE *Tablename*
CHECK CONSTRAINT *ForeinKey_Name*;
You could implement ON UPDATE CASCADE in your table.
see MySQL documentation

Adding column with existing table which have primary key

I need your help...., Please help me
I want to add a new primary key to an existing table which already has 3 columns as composite primary key. But, I do not want to drop the old primary key, since there are many records and the old primary key also have relationship with other table
When I am using this query:
alter table hem154
add indexNO uniqueidentifier default newid()
alter table hem154
add CONSTRAINT pk_hem154_indexNo PRIMARY KEY (PK_indexNO)
Note:
Hem154 ~ Table Name
indexNo ~ Column Name which will to added
I get this runtime error:
Msg 1779, Level 16, State 0, Line 1
Table 'hem154' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Please help me, how can I do it???
Thanks
Drop all primary keys and add Again all primary keys
ALTER TABLE hem154
DROP PRIMARY KEY,ADD PRIMARY KEY (col1,col2,indexNO);
You can only have one primary key per table. You can either add a second table that maps your new PK to the old PK, or drop the old PK and add the new one. Dropping the PK won't drop the columns, it just stops using them as the composite key. Any tables that were relying on the old key should probably be updated as well to support whatever answer you decide on.
First DROP existing PRIMARY KEY and ADD new composite PRIMARY KEY.
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO
and then try your code
There is no easy way of doing this. From your question, I understand that you want to add one additional column to the existing Primary Key. If they have existing relationships, then it is not possible to do this, without dropping those FK constraints first. Even if you do that, you will not be able to reestablish those FK constraints again, as you have modified the PK.
If you do not need to reestablish those FK relationships, then you can do this:
Drop all FK relationships
Drop existing PK (data will not be deleted, only the constraint will be dropped)
Add new column
Recreate PK to include the new column
However, if you cannot drop the existing FK constraints, then I am afraid this is not possible
On Microsoft SQL Server Management Studio:
Select/highlight both columns
Right click either
Press "Set primary key"

Foreign key linked with primary key in same table

I have a table Categories with columns Id, ParentId (for "subcategories" whom can have any level of nesting) and some other. Using SQL Server 2012 I can't make foreign key in same table, FK_Categories_Categories (Id -> ParentId).
Error message is
'Categories' table
- Unable to create relationship 'FK_Categories_Categories'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories". The conflict occurred in database "pokupaykadb", table "dbo.Categories", column 'Id'.
That needs for cascade deletion of subcategories. What solution can be? It's desirable to be a some property, like cascade deletion from another table by foreign key
http://i.stack.imgur.com/kXiMS.png
If there are orphaned records that does not meet your constraint criteria - delete them before creating the foreign key.
Usually there are few records which doesn't go by the new constraint and that the DBMS doesn't allow to create the constraint.
In the case of orphaned values, the first occurrence is provided in the error label with the value that is orphaned.
It would certainly have helped to see what code you have tried to execute.
Below is a valid table definition :
CREATE TABLE dbo.Categories
(
Id int NOT NULL IDENTITY(-2147483648, 1)
CONSTRAINT PK_Categories PRIMARY KEY
, ParentId int NOT NULL
CONSTRAINT FK_Categories_ParentId
FOREIGN KEY (ParentId) REFERENCES dbo.Categories
)

Resources