How to add foreign key to an existing column in SQL Server 2012 - sql

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.

Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)

ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);

CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Related

Create table with foreign key to an other table created below in sql file

My problem is that i have two tables with each table having a foreign key to the other table.
Each time , i execute the SQL file containing the creation of the two tables, it gives me an error that he doesn't find the other table. I'm working with sqlplus to execute the sql file.
Here's an example of SQL file i tried with :
create table A(
Age number(3),
name number(3) constraint A_FK references B(name))
/
create table B(
Age number(3) constraint B_FK references A(Age),
name number(3))
And even if i reverse the order, it gives the same error.
Thanks for help.
This is a problem of cycles in foreign keys. One method is to add all foreign keys after table creation (as I think the other answers propose).
You can also just do that for the first table:
create table A (
Age number(3) primary key,
name number(3)
);
create table B (
name number(3) primary key,
Age number(3),
constraint B_FK foreign key (age) references A(Age)
);
alter table B add constraint A_FK foreign key (name) references B(name);
Here is a db<>fiddle.
Notes:
Foreign keys should reference primary keys, so I added that declaration as well.
I recommend making the primary key the first column in the table.
You can also define the constraint inline for one of the tables (i.e. age number(3) constraint b_fk references a(age)).
The table column(s) that is referred by a foreign key must exist at the time when the constraint is created. Since you have some kind of cyclic reference between the tables, you need to do this in three steps:
first create one table without the foreign key
create the second table (with its foreign key)
finally add the foreign key to the first table with an alter table statement
You also need the referred column to have a unique or primary key constraint set up, otherwise you would get error ORA-02270: no matching unique or primary key for this column-list.
create table A(
age number(3) primary key,
name number(3)
);
create table B(
age number(3) constraint B_FK references A(Age),
name number(3) primary key
);
alter table A add constraint A_FK foreign key (name) references B(name);
Demo on DB Fiddle
Side note: I am quite suspicious about your sample structure, but this could be because your oversimplified it in the question.
It fails because the reference table doesn't exist yet.
Create the tables without the key first. Then drop one and recreated it with the reference. Then drop the 2nd and recreate it with the reference.
Create table first and then ADD the CONSTRAINT
ALTER TABLE A
ADD FOREIGN KEY (name) REFERENCES B(name);
ALTER TABLE B
ADD FOREIGN KEY (age) REFERENCES A(age);

Defining foreign key for a composite primary key in SQL Server

I have two tables: Ticket and TicketRelation. I am trying to relate 2 Tickets using the TicketRelation table.
I want to add a cascade constraint to both foreign keys.
I am using SQL Server Management Studio to add the constraints but I get this error:
Introducing FOREIGN KEY constraint 'FK_destiny_ticket' on table 'ticketRelation' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I also tried to do this with a trigger, but I am not sure how to define it.
Here I provide the tables definitions:
This is the base entity TICKET
CREATE TABLE ticket
(
ticket_id BIGINT,
some_data VARCHAR (50),
CONSTRAINT PK_ticket PRIMARY KEY (ticket_id)
);
and the relational table TICKETRELATION
CREATE TABLE ticketRelation
(
origin_ticket BIGINT,
destiny_ticket BIGINT,
relation_data VARCHAR (50),
CONSTRAINT PK_ticket_relation PRIMARY KEY (origin_ticket, destiny_ticket),
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id),
CONSTRAINT FK_destiny_ticket FOREIGN KEY (destiny_ticket)
REFERENCES ticket(ticket_id),
)
I want to add an ON DELETE CASCADE constraint to both foreign keys:
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- I want to add this --
CONSTRAINT FK_destiny_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- and this --

How to add unique constraint as foreign key ?

I am trying to add unique constraint as foreign key by this statement:
ALTER TABLE SOME_TABLE ADD(
CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID) UNIQUE (S_ID)
);
I thought that this statement is correct, but all time I got "missing right parenthesis error". Probably I have wrong order of key words.
Could you give me advice how to create an unique constraint ?
I red this issue:
Add a unique constraint of a sql table as foreign key reference to an another sql table
but still I have problem with this.
First, you don't need parentheses. Second, this is two constraints and you might as well give both names:
ALTER TABLE SOME_TABLE
ADD CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID);
ALTER TABLE SOME_TABLE
ADD CONSTRAINT UNQ_ST_S_ID UNIQUE (S_ID);

There are no PK in the referenced table. Why?

I have the following T-SQL to create 3 SQL tables:
create table dbo.Posts
(
Id int identity not null
constraint PK_Posts_Id primary key clustered (Id),
Active bit not null
constraint DF_Posts_Active default (0)
);
create table dbo.PostsLocalized
(
Id int not null,
Culture int not null
constraint CK_PostsLocalized_Culture check ([Culture] in ('1', '2', '3')),
[Text] nvarchar (200) not null,
constraint PK_PostsLocalized_Id_Culture primary key clustered (Id, Culture)
);
create table dbo.Tags
(
Id int identity not null
constraint PK_Tags_Id primary key clustered (Id),
Name nvarchar not null
);
create table dbo.PostsLocalized_Tags
(
PostLocalizedId int not null,
TagId int not null,
constraint PK_PostsLocalized_Tags_Post_PostLocalizedId_TagId primary key clustered (PostLocalizedId, TagId)
);
Then I have added the following constraints:
alter table dbo.PostsLocalized
add constraint FK_PostsLocalized_Id foreign key (Id) references dbo.Posts(Id) on delete cascade on update cascade;
alter table dbo.PostsLocalized_Tags
add constraint FK_PostsLocalized_Tags_PostLocalizedId foreign key (PostLocalizedId) references PostsLocalized(Id) on delete cascade on update cascade,
constraint FK_PostsLocalized_Tags_TagId foreign key (TagId) references Tags(Id) on delete cascade on update cascade;
But I get the following error:
There are no primary or candidate keys in the referenced table 'PostsLocalized' that match the referencing column list in the foreign key 'FK_PostsLocalized_Tags_PostLocalizedId'.
How can I solve this?
Thank You,
Miguel
SQL Server mandates that foreign key references be to a primary key or unique key. The foreign key reference has to be to all the columns that constitute the primary/unique key. The documentation says:
In a foreign key reference, a link is created between two tables when
the column or columns that hold the primary key value for one table
are referenced by the column or columns in another table. This column
becomes a foreign key in the second table.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY
KEY constraint in another table; it can also be defined to reference
the columns of a UNIQUE constraint in another table. A FOREIGN KEY
constraint can contain null values; however, if any column of a
composite FOREIGN KEY constraint contains null values, verification of
all values that make up the FOREIGN KEY constraint is skipped. To make
sure that all values of a composite FOREIGN KEY constraint are
verified, specify NOT NULL on all the participating columns.
The primary key in PostsLocalized contains the culture column, so you need to add it into the foreign key reference.
Your PK on PostsLocalized table is complex consisting of two columns - id and culture and you are trying to create FK on only one of those columns which is not possible.
You'll have to either add Culture column on PostsLocalized_Tags and use them both in foreign key or remove Culture from your PK on PostLocalized

two columns referencing a single column in another table

A similar question is asked here multiple foreign keys referencing single column in other table
but the syntax is not shown in the answer. I would like to know how this can be accomplished in SQL server. The following syntax gives error
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID, AdvisorID) REFERENCES Person (PersonID)
;
ERROR: Number of referencing columns in foreign key differs from number of referenced columns, table 'ItemIssue'.
-- Create Tables
CREATE TABLE ItemIssue (
ItemIssueID int identity(1,1) NOT NULL,
PersonID int,
AdvisorID int,
)
;
CREATE TABLE Person (
PersonID int NOT NULL,
Name nvarchar(500),
)
;
You need to define two foreign keys, one for each column:
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID) REFERENCES Person (PersonID)
;
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemAdvisor_Person
FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID)
;
It is impossible to create one foreign key for two columns referencing one column. Create them seperate:
ALTER TABLE ItemIssue
ADD CONSTRAINT FK_ItemIssue_Person_Person FOREIGN KEY (PersonID) REFERENCES Person (PersonID),
ADD CONSTRAINT FK_ItemIssue_Advisor_Person FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID);
To define two foreign keys, one for each column-
Table
Contract - HospidPharmacyId Column
Hospice- HospiceID PK
Pharmacy PharmacyId Pk
Using Following Query we can apply 2 Foreign Key for 1 column.
Alter Table Contract
Add Constraint fk_pharmacyID Foreign Key ([HospIDPharmID]) references Pharmacy([PharmacyID])
Alter TAble contract
Add Constraint Fk_hospId Foreign key ([HospIDPharmID]) references Hospice(HospiceID)
In the Contract Table for column-HospidPharmacyId we can insert common value in both the
tables. those which are present in hospice & not in Pharmacy then we cant insert that value in
contract table & vice versa.