update statement conflicted with foreign key constraint - sql-server

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

Related

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

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.

SQL Server : rename primary key

I have a table doc.MyTable which I want to deprecate by renaming to doc._MyTable. I then want to create a new doc.MyTable with the same primary key that the old doc.MyTable had. The problem is that SQL Server says that primary key already exists. So that means I need to rename the old primary key too.
I tried the following:
EXEC SP_RENAME 'doc.MyTable', '_MyTable'
-- Method 1
EXEC SP_RENAME 'PK_MyTable', 'PK__MyTable'
-- Method 2
ALTER TABLE [doc].[_MyTable] DROP CONSTRAINT [PK_MyTable]
ALTER TABLE [doc].[_MyTable] ADD CONSTRAINT [PK__MyTable]
PRIMARY KEY CLUSTERED
(
[document_id] ASC,
[line_id] ASC,
[sub_line_id] ASC
)
-- Create new table
CREATE TABLE [doc].[MyTable] (
... columns
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED (
... key columns
)
... extra conditions
Method 1 throws this error:
No item by the name of 'PK_MyTable' could be found in the current database 'db_dev', given that #itemtype was input as '(null)'.
While method 2 throws this:
Violation of PRIMARY KEY constraint 'PK_MyTable'. Cannot insert duplicate key in object 'PK.MyTable'. The duplicate key value is (10358930, 336000, 0).`
When I try to create the new primary key for the new table.
I'm only using one of the two "Methods" at a time. How do I fix the issue?
Try following solution:
EXEC sp_rename '[TableSchema].[TableName].[ConstraintName]', 'NewConstraintName'
Example:
EXEC sp_rename '[doc].[_MyTable].[PK_MyTable]', '[PK__MyTable]'
When renaming your primary key, prefix the primary key name with the schema and table name like so:
create schema doc authorization dbo;
go
create table doc.MyTable (
id int not null
, constraint pk_MyTable primary key clustered (Id)
);
exec sp_rename N'doc.MyTable.pk_MyTable', N'pk__MyTable';
exec sp_rename N'doc.MyTable', N'_MyTable', N'object';
create table doc.MyTable (
id int not null
, constraint pk_MyTable primary key clustered (Id)
);
rextester demo: http://rextester.com/OBIB87116
If you were using the default schema dbo, you would not need to prefix the schema and table name to rename the primary key with sp_rename.
Cant you delete it from your original table and re-create it with the name you want?
ALTER TABLE dbo.YourOldTable
DROP CONSTRAINT YourConstraintname;

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
)

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I have a table called patient_address, which reference a PK key in patient table. But if I try to run one of the following statements :
update patient set id_no='7008255601088' where id_no='8008255601089'
update patient_address set id_no='7008255601088' where id_no='8008255601089'
I get this error message:
"The UPDATE statement conflicted with the REFERENCE constraint
"FK__patient_a__id_no__27C3E46E". The conflict occurred in database
"PMS", table "dbo.patient_address", column 'id_no'." or "The
UPDATE statement conflicted with the FOREIGN KEY constraint
"FK__patient_a__id_no__27C3E46E". The conflict occurred in database
"PMS", table "dbo.patient", column 'id_no'." .
Does any body know the possible cause ? Thanks.
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.
Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:
You can also set the rule using T-SQL:
ALTER TABLE YourTable
DROP Constraint Your_FK
GO
ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO
Hope this helps
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
It sometimes happens when you try to Insert/Update an entity while the foreign key that you are trying to Insert/Update actually does not exist. So, be sure that the foreign key exists and try again.
In MySQL
set foreign_key_checks=0;
UPDATE patient INNER JOIN patient_address
ON patient.id_no=patient_address.id_no
SET patient.id_no='8008255601088',
patient_address.id_no=patient.id_no
WHERE patient.id_no='7008255601088';
Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check.
Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.
This was the solution for me:
-- Check how it is now
select * from patient
select * from patient_address
-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient
set id_no='7008255601088'
where id_no='8008255601088'
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address
set id_no='7008255601088'
where id_no='8008255601088'
-- Check how it is now
select * from patient
select * from patient_address
Reason is as #MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.
exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'
exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
Source:
https://stackoverflow.com/a/161410/3850405
I would not change the constraints,
instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.
Then you can remove the initial primary key row with id_no =7008255601088.
Three steps include:
Insert duplicate row for new id_no
Update Patient_address to point to new duplicate row
Remove the row with old id_no
I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation.
You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

Error upon creating tables in sqlplus

I'm new to sqlplus and was trying to run a sql script that creates a few tables, but once I try to run it, it gives me an error saying that the table or view doesnt exist and I dont know how to fix this error.
My script is:
drop table Borrower;
create table Borrower (
bid char(100) not null,
password char(100) not null,
name char(100) null,
address char(100) null,
phone char(100) null,
emailAddress char(100) null,
sinOrStNo char(100) null,
expiryDate date null,
--type ENUM('student','faculty','staff'),
type char(100) not null,
--CONSTRAINT Btype_check CHECK (type IN ('student','faculty','staff')),
FOREIGN KEY (type) references BorrowerType(type),
PRIMARY KEY (bid));
grant select on Borrower to public;
"unique/primary keys in table referenced by foreign keys "
Data integrity is crucial to a properly run database so Oracle will not let us drop a table if its primary key is referenced by another table's foreign key. So it hurls ORA-02449.
So, given this set up:
create table t_parent (
id number not null
, constraint tp_pk primary key (id)
);
create table t_child (
id number not null
, p_id number not null
, constraint tc_pk primary key (id)
, constraint tc_tp_fk foreign key (p_id)
references t_parent (id)
);
There are three ways to drop table t_parent.
run drop table t_child first: no child table, no foreign key.
Remove the blocking foreign key: alter table t_child drop constraint tc_pc_fk.
A variant on the previous one, let the database figure out the foreign keys:
drop table t_parent cascade constraints.
The first option is the most proper, because it leaves the database in a valid state (no tables, no possibility of data integrity corruption). The valid use for the third approach is a script which razes all the tables from a schema: it's easy to generate such a script from the data dictionary.
The order that you drop or create tables are important because if you have foreign keys referencing another table, you cant delete that table before deleting your own table.
In this example, the Borrower table has to be dropped before the BorrowerType table.

Resources