SQL Update error. FK Conflict - sql

I am trying to change the name of a group from ASSY to Manufacturing but am running into some dificulties. It is on a sql server database. I ran the query below.
Update groups
set group_code= 'Manufacturing'
where site_code = 'TMMBC' and group_code = 'ASSY' and group_description = 'Manufacturing'
But it returned with this error - "The UPDATE statement conflicted with the REFERENCE constraint "user_groups_FK_2". The conflict occurred in database "eci", table "dbo.user_groups"."
Is there a way I can update both tables at the same time to bypass this error?

Is there a way I can update both tables at the same time to bypass
this error?
Yes. You can define the foreign key to cascade on update.
I would consider restructuring it so that groups has an integer surrogate key though and have the textual description as a separate column.
This avoids having to repeat the relatively long string Manufacturing possibly many times in the child table.

Assuming your definition for table user_groups looks something like:
create table dbo.user_groups (
group_code varchar(100),
-- other fields
constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code)
);
You would change the table definition to have the foreign key cascade, like:
create table dbo.user_groups (
group_code varchar(100),
-- other fields
constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code) on delete cascade on update cascade
);
Or through ALTER TABLE statements:
alter table dbo.user_groups drop constraint user_groups_fk_2;
alter table dbo.user_groups add constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code) on delete cascade on update cascade;

Related

create a constraint between tables

I am new to sql and have not have much experience in it
Trying to create a relationship between two tables using a constraint.
adding a unique constraint and relationship for force the userid and consumerid between table1 and table2
any sample will help me
Thanks
You can use this FOREIGN KEY (blabla) REFERENCES secondTable(blabla) but only if the table is not created yet. Write it inside your CREATE TABLE query.
But if it already exists you can add it using ALTER TABLE tablename ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`blabla`) REFERENCES `secondTable` (`blabla`) ON DELETE CASCADE ON UPDATE CASCADE;

Alter Foreign Key Constraint Primary Key Error

I'm trying to drop and recreate a foreign key constraint, but I get an error
There are no primary or candidate keys in the referenced table 'inventory' that match the referencing column list in the foreign key 'fkInventory_VendorsInventory'.
I have already gone into the table design for both tables referenced in the code, and ensured that the column being referenced is a primary key.
ALTER TABLE inventory_vendors
DROP CONSTRAINT fkInventory_VendorsInventory;
ALTER TABLE inventory_vendors
ADD CONSTRAINT fkInventory_VendorsInventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
I have done such a drop and recreation before with no problems at all with another set of tables (unfortunately i don't remember which tables they were).
As you mentioned in comments, you have 2 primary key columns in the Inventory table:
one is itemnum, the other is store_id
I prepare a sample SQL here: 2 tables created
CREATE TABLE inventory
(
itemnum INT,
store_id INT,
inventoryDesc char(200),
primary key (itemnum, store_id)
);
CREATE TABLE inventory_vendors
(
inventory_vendors int,
itemnum INT,
store_id INT,
VendorDetails varchar(200),
primary key (inventory_vendors)
);
Create Unique constraint for one of the primary key. Here I am creating UNIQUE constraint for itemnum column
ALTER TABLE inventory
ADD CONSTRAINT [IX_inventory] UNIQUE ( [itemnum] )
GO
Then execute your script for creating the foreign key constraint on inventory_vendors for itemnum column and you can drop them as well.
ALTER TABLE inventory_vendors
ADD CONSTRAINT fk_Inventory_Vendors_Inventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE inventory_vendors
DROP CONSTRAINT fk_Inventory_Vendors_Inventory;
Hope this might help you..

Does designating a foreign key automatically take care of updates to the foreign table's value?

I have two tables: student and faculty
I added a column to the student table that is a foreign key that references a column in faculty.
Let's say that a faculty's id changes. Based on my code below, will my student table update accordingly? Or do I need to do anything extra to ensure that it updates? For example, pretend that James's id updates from 1 to 99. Will the advisorid column of student update accordingly?
Note - I am using LINQPad and I have no way to test this because when I try to make a change to the referenced table I get an Error 547: The UPDATE statement conflicted with the REFERENCE constraint "FK__enroll__studenti__178D7CA5". The conflict occurred in database "tempdb", table "dbo.enroll", column 'studentid'.
alter table student
add advisorid int foreign key(advisorid) references faculty(facultyid);
update student set advisorid = 1 where studentid = 1;
select * from student
select * from faculty;
As you've seen, by default, updates on the key a foreign key is based of do no propagate to the dependent columns. You can get such a behavior by specifying an on update clause:
alter table student
add advisorid int foreign key(advisorid) references faculty(facultyid)
on update cascade;
EDIT:
To answer the question in the comments, the behavior could also be defined when deleting a row:
alter table student
add advisorid int foreign key(advisorid) references faculty(facultyid)
on delete cascade
on update cascade;
In Oracle ON UPDATE CASCADE does not work. Here I will demonstrate an alternative update scenario.
Instead of specifying ON UPDATE CASCADE it is possible to deferring the check of a contraint to the end of a transaction. Therefore the constraint must be DEFERRABLE. Unfortuantely the constraint could not be modified so that it must dropped and recreated.
Here is an Example:
CREATE TABLE parent_ (
pid NUMBER CONSTRAINT pk_parent PRIMARY KEY,
c1 VARCHAR2(50)
);
CREATE TABLE child_ (
cid NUMBER,
pid NUMBER CONSTRAINT fk_child_parent REFERENCES parent_(pid) ON DELETE CASCADE, --DEFERRABLE,
c1 VARCHAR2(50)
);
INSERT INTO parent_ VALUES (1, 'two');
INSERT INTO child_ VALUES (2, 1, 'two');
COMMIT;
An update of the primary key or foreign key will lead to an oracle exception
UPDATE parent_ SET pid = 2
Fehlerbericht -
SQL-Fehler: ORA-02292: integrity constraint (ME.FK_CHILD_PARENT) violated - child record found
02292. 00000 - "integrity constraint (%s.%s) violated - child record found"
*Cause: attempted to delete a parent key value that had a foreign
dependency.
*Action: delete dependencies first then parent or disable constraint.
UPDATE child_ SET pid = 2
Fehlerbericht -
SQL-Fehler: ORA-02291: integrity constraint (ME.FK_CHILD_PARENT) violated - parent key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
Now the foreign key will be re-created as deferrable. It will still lead to foreign key constraint violations but it can be set to deferred per session. The advantage is that all other session still behave as before.
ALTER TABLE child_ DROP CONSTRAINT fk_child_parent;
ALTER TABLE child_ ADD CONSTRAINT fk_child_parent FOREIGN KEY (pid) REFERENCES parent_(pid) ON DELETE CASCADE DEFERRABLE;
ALTER SESSION SET CONSTRAINTS = DEFERRED;
UPDATE parent_ SET pid = 2;
UPDATE child_ SET pid = 2;
COMMIT;
ALTER SESSION SET CONSTRAINTS = IMMEDIATE;
The DEFERRABLE attribute can also be set when creating a foreign key (also inline). Find more on that in the official documentation

Removing a primary key column in SQL Server 2008

I have a table named master_employee with a column empid as the primary key, and it has 12 rows in it. This empid has been mapped as a foreign key to another table named dep_child. I want to delete the 12 records in the master_employee table but I was unable to do it.
You were unable to do the deletes from master_employees, as there is a referential integrity with dep_child. You would need to either disable the constraint or delete the records from dep_child, before being able to delete records from master_employees
Add this constraints to your master_employee table
ALTER TABLE "master_employee"
ADD CONSTRAINT "fk_emp11"
FOREIGN KEY ("emp_id")
REFERENCES "dep_child" ("emp_id")
ON DELETE CASCADE;

Enforce a foreign-key constraint to columns of same table

How to enforce a constraint of foreign key on columns of same table in SQL while entering values in the following table:
employee:
empid number,
manager number (must be an existing employee)
Oracle call this a self-referential integrity constraint. The documentation is here for a description,
You create a self-referential constraint in the same manner you would a normal one:
alter table employees
add constraint employees_emp_man_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
;
I'm assuming that your manager_no is nullable. I've added set null here as a delete cascade would probably wipe out a significant amount of your table.
I can't think of a better way of doing this. Deleting a manager should not result in the deletion of all their employees so you have to set null and have a trigger on the table to alert you to anyone with no manager.
I always like this site, which is good for simple references. and don't forget to have an index on the FK as well or Tom will yell at you :-).
One can also utilise standard Oracle syntax to create a self-referential FK in the create table statement, which would look like the following.
create table employees
( emp_id number
, other_columns ...
, manager_no number
, constraint employees_pk
primary key (emp_id)
, constraint employees_man_emp_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
);
EDIT:
In answer to #popstack's comment below:
Whilst you can do this in one statement not being able to alter a table is a fairly ridiculous state of affairs. You should definitely analyze a table that you're going to be selecting from and you will still want an index on the foreign key ( and possibly more columns and / or more indexes ) otherwise whenever you use the foreign key you're going to do a full table scan. See my link to asktom above.
If you're unable to alter a table then you should, in descending order of importance.
Find out how you can.
Change your DB design as a FK should have an index and if you can't have one then FKs are probably not the way to go. Maybe have a table of managers and a table of employees?
SELF REFERENCES QUERY...
Alter table table_name ADD constraints constraints_name foreign key(column_name1,column_name2..) references table_name(column_name1,column_name2...) ON DELETE CASCADE;
EX- ALTER TABLE Employee ADD CONSTRAINTS Fr_key( mgr_no) references employee(Emp_no) ON DELETE CASCADE;
CREATE TABLE TABLE_NAME (
`empid_number` int ( 11) NOT NULL auto_increment,
`employee` varchar ( 100) NOT NULL ,
`manager_number` int ( 11) NOT NULL ,
PRIMARY KEY (`empid_number`),
CONSTRAINT `manager_references_employee`
FOREIGN KEY (`manager_number`) REFERENCES (`empid_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Hope it helps!