How to alter the table to add foreign key constraint referencing primary key of same table - sql

When I try to alter the table to add the foreign constraint, it is throwing the below error
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ManagerId". The conflict occurred in database "MX_STAG", table "dbo.Sales_US_User", column 'ID'.
I tried the below queries,none of them have worked.
ALTER TABLE SALES_US_USER
ADD CONSTRAINT FK_ManagerId
FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
ALTER TABLE SALES_US_USER
ADD FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
Please help

You've got the DDL right. That error is telling you that you have a row with a ManagerId that does not map to an Id. EG
use tempdb
go
drop table if exists sales_us_manager
go
create table sales_us_user(Id int primary key, ManagerId int)
insert into sales_us_user(id,managerId) values (1,2)
ALTER TABLE SALES_US_USER
ADD CONSTRAINT FK_ManagerId
FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
--Msg 547, Level 16, State 0, Line 12
--The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ManagerId". The conflict occurred in database "tempdb", table "dbo.sales_us_user", column 'Id'.
select *
from SALES_US_USER
where ManagerId not in
(select id from SALES_US_USER )

You need to delete both table data before updated database with your new migration. One of the common mistakes that you add a FK (foreign key) from table to another while any on these table contains data. The constraint happens because the FK can't be null and while you are adding the new migration the database find that the new column that will be created will be null so, delete the data in both tables first.

The issue got resolved after finding and updating the rows with an an invalid ManagerId, and then created the constraint.

Related

Unable to drop foreign key in SQL server

I am trying this query to drop a foreign key ALTER TABLE dbo.[User] DROP FOREIGN KEY FK_User_UserTypeID.
But I am getting this
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'FOREIGN'.
SQL FOREIGN KEY on CREATE TABLE : -
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
SQL FOREIGN KEY on ALTER TABLE :-
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint :-
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
NOTE
Should not have any dependency on foreign key while dropping key constraints, otherwise you will not be able to drop the constraint.

How do I change a column I created a while ago in sql to foreign key

I need to change multiple tables to foreign keys. I have used the command
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES transaction_id(item_rental_id);
The table name was financial_transactions and the column name was item_rental_id. It gives me an error saying:
Foreign key 'FK__financial__item___46E78A0C' references invalid table 'transaction_id'.
How do I resolve this?
Yes, this is a correct script to create a foreign key
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
However, if you are trying to add a foreign key constraint on a table with data already in it, you have to make sure that the item_rental_id in financial_transactions table are also in the customer_rentals table. Otherwise, you will have a referential integrity error.
To illustrate:
CREATE TABLE customer_rentals_1
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_1
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
ALTER TABLE financial_transactions_1
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_1(item_rental_id);
The scripts above will run successfully.
CREATE TABLE customer_rentals_2
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_2
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
INSERT INTO financial_transactions_2
VALUES (1000, 9999);
ALTER TABLE financial_transactions_2
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_2(item_rental_id);
But, this will have the following error since item_rental_id 9999 is not present in customer_rentals_2 table
Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__financial__item___76969D2E". The conflict occurred in database "TESTDB", table "dbo.customer_rentals_2", column 'item_rental_id'.
You have to give second table name
both way can do it
1. Add reference without name
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
2.Add reference with a name
ALTER TABLE financial_transactions
ADD CONSTRAINT FK_Financial_Transactions_Customer_Rental_Item_Rental_ID
FOREIGN KEY (item_rental_id) REFERENCES Customer_rentals(item_rental_id);

cannot alter table to add a foreign key

alter table course_relation
add foreign key (offered_By)
references department_relation(dept_cd)
alter table department_relation
add foreign key(hod)
references staff_relation(staff_no)
alter table staff_relation
add foreign key (dept_cd)
references department_relation(dept_cd)
//the third para doesn't work but the first two works fine
error message:
Msg 547, Level 16, State 0, Line 10 The ALTER TABLE statement
conflicted with the FOREIGN KEY constraint
"FK__staff_rela__dept__1BC821DD". The conflict occurred in database
"Royal_Poly_DB", table "dbo.Department_Relation", column 'Dept_Cd'.
You can't create circular foreign key references.
In this Statement
alter table department_relation
add foreign key(hod)
references staff_relation(staff_no)
In this alter query you create foreign key reference in 'department_relation' from 'staff_relation' table.
alter table staff_relation
add foreign key (dept_cd)
references department_relation(dept_cd)
In this alter query you create foreign key reference in 'staff_relation' from 'department_relation' table.
This is circular dependency of foreign key and it is allowed.

How do I make a Table's Attribute a Foreign Key within that Table?

I had to write the SQL to create the tables, attributes, and primary & foreign keys in this ERD:
http://imgur.com/VYZbwr6
In the table 'Financial_Transactions' in the ERD there is a attribute called 'previous_transaction_id' and another attribute called 'transaction_id'. In this table 'previous_transaction_id' is a Foreign Key for this table in addition to being an attribute. It references the last 'transaction_id' in the table.
Here is my SQL for the 'financial_transactions' table:
CREATE TABLE financial_transactions(
transaction_id int IDENTITY(1,1) NOT NULL,
account_id int NOT NULL,
item_rental_id int NOT NULL,
previous_transaction_id int,
transaction_type_code int NOT NULL,
transaction_date date NOT NULL,
transaction_amount money NOT NULL,
transaction_comment varchar(512) NOT NULL);
ALTER TABLE financial_transactions ADD CONSTRAINT pk_financial_transactions PRIMARY KEY (transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_accounts FOREIGN KEY(account_id)
REFERENCES accounts (account_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_customer_rentals FOREIGN KEY(item_rental_id)
REFERENCES customer_rentals (item_rental_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_transaction_types FOREIGN KEY(transaction_type_code)
REFERENCES transaction_types (transaction_type_code);
When I run my SQL (includes statements for each table in the script) I get these errors:
"Msg 1776, Level 16, State 0, Line 87
There are no primary or candidate keys in the referenced table 'financial_transactions' that match the referencing column list in the foreign key 'fk_financial_transactions_financial_transactions'.
Msg 1750, Level 16, State 0, Line 87
Could not create constraint. See previous errors."
All other statements execute normally.
What am I doing wrong?
*I used this statement originally under CREATE TABLE: previous_transaction_id int NOT NULL,
However, it resulted in the same error and when searching I saw a similar question that was fixed by removing the NOT NULL.
Here
ALTER TABLE financial_transactions ADD CONSTRAINT
fk_financial_transactions_financial_transactions
FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
You have a column referencing itself. Was that your intent or did you want to reference the transaction_id?
There is nothing wrong with defining a foreign key to the same table but you have a column referencing itself.
Try replacing:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
With:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (transaction_id);

The ALTER TABLE statement conflicted with the FOREIGN KEY constrain

I'm kind of new to scripting in SQL and I have encountered an error in one of my scripts.
The problematic section is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE dbo.WorkspaceSettings
(
Id INT NOT NULL IDENTITY PRIMARY KEY ,
ReportColorRGB1 VARCHAR(15) NOT NULL DEFAULT '61,105,138' ,
ReportColorRGB2 VARCHAR(15) NOT NULL DEFAULT '180,210,121'
)
GO
ALTER TABLE Workspace ADD WorkspaceSettingsId int NOT NULL default 1;
GO
ALTER TABLE Workspace
ADD CONSTRAINT FK_WorkspaceSettings_Workspace
FOREIGN KEY (WorkspaceSettingsId)
REFERENCES WorkspaceSettings(Id);
GO
And receive the following error message:
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_WorkspaceSettings_Workspace". The conflict occurred in database "ClearRisk2_0", table "dbo.WorkspaceSettings", column 'Id'.
Can someone please tell me where I'm going wrong?
The default value of 1 that you've specified for the Workspace.WorkspaceSettingsId column does not yet exist in your WorkspaceSettings table, hence the FK violation.
Just add the following phrase after ALter table sattement:
with nocheck
So, it will be:
Use Database_name
Go
ALTER TABLE ResultScan with nocheck
ADD CONSTRAINT FK_ResultScan_ListVM FOREIGN KEY (TypeAnVirus)
REFERENCES ListVM (Id)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO