Self Referencing FK - The UPDATE statement conflicted with the FOREIGN KEY constraint - sql-server

I have a test table employee which have self referencing FK manager_id:
CREATE TABLE employee (
employee_id int IDENTITY PRIMARY KEY,
employee_name varchar(30),
salary varchar(30),
manager_id int
);
ALTER TABLE employee
ADD CONSTRAINT sr_fk_emp_man
FOREIGN KEY (manager_id)
REFERENCES employee(employee_id)
;
INSERT INTO employee (employee_name, salary) VALUES
('ISACC NEWTON', 732611),
('ROMEO', 329827);
UPDATE employee SET manager_id = 21 WHERE employee_name = 'ROMEO';
Error occurs when I set for PK employee_id int IDENTITIY:
The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint "sr_fk_emp_man".
The conflict occurred in database "master", table "dbo.employee", column 'employee_id'.
I need to have for PK numeric column that is automatically populated.
I tried to solve a problem with adding sequence instead of IDENTITIY, adding Referential integrity for FK (ON DELETE CASCADE ON UPDATE CASCADE) and set for FK NULL value but nothing changes. I could use WITH NOCHECK Constraint but I read that is not the safest option. I am using MS SQL Server.

Related

How can we update an column with Foreign key constraint in DB2?

I have 2 Tables , please check images attached
PK: PK
FK: FK
P_Id in Pk table is the primary key
and P_Id in FK table is the foreign key.
I need to add 10 to all records in P_Id column of both PK and FK table( meaning they need to match always)
I know in MS SQL we can easily update cascade as follows:
ALTER TABLE FK
ADD CONSTRAINT FK_P_Id
FOREIGN KEY (P_Id)
REFERENCES PK (P_Id) ON UPDATE CASCADE
and then update the rows of PK , which will automatically update FK too.
update A
set A.P_Id= A.P_Id + 10
from PK A inner join FK B
on A.P_Id = B.P_Id
But, i am not sure how this works in DB2.. can someone please help?
How can i get this to work?
Thanks in advance
Swat
use
SET FOREIGN_KEY_CHECKS = 0;
update both the tables;
and then
SET FOREIGN_KEY_CHECKS = 1;
--remove you foreign key
ALTER TABLE YOURLIB.FK
drop CONSTRAINT YOURLIB.FK_P_Id;
--update FK table
update YOURLIB.FK
set P_Id=P_Id+10;
--update PK table (force)
update YOURLIB.PK overriding system value
set P_Id=P_Id+10;
--recreate foreign key
ALTER TABLE YOURLIB.FK
ADD CONSTRAINT YOURLIB.FK_P_Id
FOREIGN KEY (P_Id)
REFERENCES YOURLIB.PK (P_Id)
ON DELETE RESTRICT;
--If you id on PK is autoincremented, restart it (here 123456 in example but you must found max of id in your PK table --> select max(p_id) from yourlib.pk)
ALTER TABLE YOURLIB.PK
ALTER COLUMN P_Id
RESTART with 123456;
you can modify a key to force like this, only if you update dont create double value key (example your key + 10 already exist in your table), else you must remove the primary key before update (Dangerous, be carefull if someone are working on your table). Ok course you must remove foreign key for do it
update pk f0 overriding system value
set f0.id=f0.id+10
where exists
(
select * from fk f1
where f0.id=f1.id
)

update statement conflicted with foreign key constraint

I have problem on updating column set as primary key, even I made on update set default
this is my code for creating tables, I set on update set default
create table department(
id int default 10 primary key,
name varchar(50)
);
create table employee
(
id int primary key,
dept_id int default 40 foreign key references department(id) on update set default on delete set default,
name varchar(40)
);
after that, I inserted data to the tables
insert into department
values
(1,'hr'),
(2,'programming'),
(3,'telesales'),
(4,'database')
insert into employee
values
(1,1,'mohammed'),
(2,2,'magd'),
(3,1,'soha'),
(4,3,'sameh'),
(5,4,'ashraf')
but, when I run this code to update the column id
update department
set id = 44 where id = 4
I get that error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK__employee__dept_i__571DF1D5". The conflict occurred in database "test", table "dbo.department", column 'id'.
The statement has been terminated.
but I do not know where is my fault!
thanks
Use ON UPDATE CASCADE in the foreign key constraint, like so:
create table employee
(
id int primary key,
dept_id int default 40 foreign key references department(id) on update cascade on delete set default,
name varchar(40)
);
If there is any update to the id column value, dept_id also gets updated to follow the changed value.
Because employee table have dept_id column *constraint* with id column of department. This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.
If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade
You can try this:
ALTER TABLE employee
DROP Constraint FK__employee__dept_i__571DF1D5
GO
ALTER TABLE employee
ADD CONSTRAINT New_FK_Constraint
FOREIGN KEY (dept_id) REFERENCES department (id)
ON DELETE CASCADE ON UPDATE CASCADE
GO
it's normally to that error to appear, You have a foreign key relation and you then change the value.
Use ON UPDATE CASCADE in the foreign key constraint
If you don't want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId

Foreign Key error SQL Server

I have three tables that are to be connected using a foreign key.
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(1) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE booking
(
customerID INT,
packageCode VARCHAR(6) UNIQUE,
bookingDate DATE NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID),
CONSTRAINT bookingFK
FOREIGN KEY (customerID)
REFERENCES customer (customerID)
ON DELETE CASCADE
);
CREATE TABLE package
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(1) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode),
CONSTRAINT packageFK
FOREIGN KEY (packageCode)
REFERENCES booking (packageCode)
ON DELETE CASCADE
)
I got the Foreign key between customer and booking set properly, its purpose is to delete all associated bookings with that customer. I am currently trying to do the same between package and bookings, When a package record is deleted, it should also delete the corresponding records. I continue to get the error
The INSERT statement conflicted with the FOREIGN KEY constraint
"packageFK". The conflict occurred in database "travel", table
"dbo.booking", column 'packageCode'.
Im not quite sure what this is referencing as I have encountered this error before and fixed it, unfortunately... I cannot in this case.
All help is greatly appreciated.
Thanks,
Bryan
Since you want to delete all booking rows when a package is deleted, the package table must be the primary table and the booking table must reference the package table. Remove the foreign key constraint from the table and add the following to the bookings table:
CONSTRAINT booking_packageFK
FOREIGN KEY (packageCode)
REFERENCES package (packageCode)
ON DELETE CASCADE
You should also remove the UNIQUE constraint from the packageCode on the booking table.
I don't think you have your foreign key relationship set up correctly even between Customer and Booking.
In your Create Table customer following tells the server that CustomerId is the Primary Key in customer table:
CONSTRAINT customerPK
PRIMARY KEY (customerID)
In your Create Table booking following tells the server that CustomerId is the Primary Key as well as a Foreign Key that references customer:
CONSTRAINT bookingPK
PRIMARY KEY (customerID),
CONSTRAINT bookingFK
FOREIGN KEY (customerID)
REFERENCES customer (customerID)
ON DELETE CASCADE
Similarly in your package table you have set packageCode as both primary and foreign key.
What I think you need is:
CustomerId in Customer table should be the primary key
There should be a BookingId and a CustomerId in the Booking table. BookingId will be the primary key and CustomerId will be the foreign key that references Customer.
There should be a BookingId in the Package table. It will be a foreign key that references Booking.

Add a unique constraint of a sql table as foreign key reference to an another sql table

how to add a unique constraint of a sql table as foreign key reference to an another sql table in sql server 2005
In order to add FK constraint (in child table to parent table) you have to add unique constraint to parent table columns of relationship.
All the rest is optional or has nothing to do with FK:
no obligatory need of any primary key
no need of uniqueness in child table colums(s)
The parent table (in such FK relation) is frequently called (including by SSMS) as Primary Key table but PK is not must, unique key/constraint in parent table is enough (as PK is unique, it is particular case of unique constraint in parent table).
Drop TableA and TableB from answer by Matt, which is confusing for beginners,
and recreate them as
CREATE TABLE parentB--TableB
(
PK1 INT NOT NULL,
PK2 INT NOT NULL,
--I would not have additional non-referenced data in parent table,
--rather in child table
--SomeData VARCHAR(1000),
--CONSTRAINT PK_TableB PRIMARY KEY CLUSTERED (PK1, PK2)
)
CREATE TABLE childA--TableA
(
--PK INT, -- NOT NULL,
FK1 INT-- NOT NULL, -- Or NULL, if you''d rather.
FK2 INT --NOT NULL --,
, SomeData VARCHAR(1000)
--CONSTRAINT PK_TableA PRIMARY KEY CLUSTERED (PK),
--CONSTRAINT FK_TableA_FK1FK2 FOREIGN KEY (FK1, FK2) REFERENCES TableB (PK1, PK2),
--CONSTRAINT Cons2cols UNIQUE(FK1, FK2)
)
Now, in order, to add FK
ALTER TABLE childA
ADD
--constraint FK1_childA
--this is optional, if one needs to add his own custom name
FOREIGN KEY (FK1) REFERENCES parentB(PK1);
you should first create unique constraint on corresponding referenced column in parent table column:
ALTER TABLE parentB ADD
--CONSTRAINT YourUniqueName --uncomment for adding your own name to constraint
UNIQUE(PK1)
Similarly for 2 columns foreign key constraint
(first, you need corresponding unique constraint in parent table):
ALTER TABLE parentB ADD
--CONSTRAINT YourUniqueName --for adding your own name to unique constraint
UNIQUE(PK1,PK2)
ALTER TABLE childA
ADD
--constraint yourUniqueName --uncomment for adding your own name to FK constraint
FOREIGN KEY (FK1, FK2) REFERENCES parentB(PK1, PK2);
Apologies but I'm not really sure what you're asking here. Giving more of an example with table definitions would help! I think you're saying you have two columns in TableA in a unique constraint named "Cons2cols", and you also want these two columns to be a FK to a two column PK / unqiue pair in TableB.
That works as follows, if you're creating the tables from scratch:
CREATE TABLE TableB (
PK1 INT NOT NULL,
PK2 INT NOT NULL,
SomeData VARCHAR(1000),
CONSTRAINT PK_TableB PRIMARY KEY CLUSTERED (PK1, PK2)
)
CREATE TABLE TableA (
PK INT NOT NULL,
FK1 INT NOT NULL, -- Or NULL, if you''d rather.
FK2 INT NOT NULL,
CONSTRAINT PK_TableA PRIMARY KEY CLUSTERED (PK),
CONSTRAINT FK_TableA_FK1FK2 FOREIGN KEY (FK1, FK2) REFERENCES TableB (PK1, PK2),
CONSTRAINT Cons2cols UNIQUE(FK1, FK2)
)
If the tables already exist, you can add in these same constraints after the fact:
ALTER TABLE TableA ADD CONSTRAINT FK_TableA_FK1FK2 FOREIGN KEY (FK1, FK2) REFERENCES TableB (PK1, PK2);
ALTER TABLE TableA ADD CONSTRAINT Cons2cols UNIQUE(FK1, FK2);
Either way, TableA now has a unique, 2 column FK to another table.
You need to keep in mind that adding a FK on a column does not automatically put an index on that column. You'll need to do this in two steps.
1) Make a column in your table a FK to a parent table.
2) Add a unique constraint on that same column
Forget about the unique constraint for now. Just create your new foreign key on the two columns.
ALTER TABLE dbo.PurchaseDetail
ADD FOREIGN KEY (Customer, Product)
REFERENCES dbo.Purchase (Customer, Product)
I prefer this approach where this table references another table (transaction_log):
CREATE TABLE transaction_settings_log
(
transaction_fk UUID NOT NULL
CONSTRAINT transaction_log_pkey REFERENCES transaction_log (id) UNIQUE,
group_selected BOOLEAN DEFAULT TRUE,
leg_closed BOOLEAN DEFAULT FALSE
);

multiple constraint keys

if i have tabled:
Resource (id (PK), name)
Manager (id(PK), resource_id (FK), manager_resource_ID(FK))
Should resource_id and manager_id both be foreign keys into the Resource table.
i obviously dont want to enter any values in each of those columns that are not proper resources
when i add the first relationship (resource_id <-> id) it works fine but
when i add the second one (manager_resource_id <-> id) it fails with the error:
Unable to create relationship [ . . .] The ALTER TABLE statement conflicted with the FOREIGN KEY constraint [... ]. The conflict occured in table Resource, column id
or do i need to break this out into 3 tables?
Resource(id, first, last)
Resource_manager(id, resource_id, manager_ID)
Manager(id)
Just a hint:
UPDATE:
If your model has employee-manager as many-to-many (bit unusual) then you could do:
CREATE TABLE Employee
(
EmployeeID int NOT NULL
,[Name] varchar(50)
)
go
ALTER TABLE Employee ADD
CONSTRAINT PK_Employee PRIMARY KEY CLUSTERED (EmployeeID ASC)
go
CREATE TABLE Manager
(
EmployeeID int NOT NULL
,ManagerID int NOT NULL
)
go
ALTER TABLE Manager ADD
CONSTRAINT PK_Manager PRIMARY KEY CLUSTERED (EmployeeID ASC, ManagerID ASC)
,CONSTRAINT FK1_Manager FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID)
,CONSTRAINT FK2_Manager FOREIGN KEY (ManagerID) REFERENCES Employee(EmployeeID)
,CONSTRAINT chk_Manager CHECK (EmployeeID <> ManagerID)
go
You have to create the foreign keys in the Manager table.

Resources