On update cascade for a self-referencing key - SQL Server - sql-server

I am trying to figure out how to perform on update cascade on a self-referencing temporal table using triggers. While I found that this post (On delete cascade for self-referencing table) is the closest it can get to my answer, I had the below questions:
The Answer and the question seems incomplete in the post. Can you please tell me what is contained in Deleted table in the post? What is id in Deleted table and Comments table? Is it a primary key? What if primary key is a pair of columns? Also, I am not sure why is IDs inside the CTE IDs. Seems incorrect. I am not sure.
What would the on update cascade specific trigger look like if the table has other foreign key constraints?
I have the below table setup. Can you please help me create a trigger for it on update cascade on the foreign key FK_Son_Height_Weight?
I could use a surrogate key here but there are several tables that have foreign key reference to PK_Height_Weight. Is there a way to make sure I dont need a surrogate key?
(Note: the table has been modified for privacy reasons)
CREATE TABLE no.Man (
Height varchar(100) NOT NULL,
Weight varchar(50) NOT NULL,
CONSTRAINT PK_Height_Weight PRIMARY KEY (Height, Weight),
CONSTRAINT FK_Weight FOREIGN KEY (Weight)
REFERENCES no.Human (Weight)
On Update Cascade,
Son_Height varchar (100) NOT NULL,
Son_Weight varchar (50) NOT NULL,
CONSTRAINT FK_Son_Height_Weight FOREIGN KEY (Son_Height, Son_Weight)
REFERENCES no.Man(Height,Weight)
On Update Cascade
)

Since the table is a temporal table, only 'After Update' trigger can be used on it and not the 'Instead Of Update' trigger (link for reference). I used the below solution for now to set stuff to null. This isnt a complete answer - yet trying to share with the community what I know.
CREATE or ALTER TRIGGER no.Weight_Height
ON no.Man
After UPDATE
AS
Set nocount on
IF ( UPDATE (Height) AND UPDATE (Weight) )
;With BA_DEL_Join as
(
select d.Height as d_Height, d.Weight as d_Weight,
d.Son_Height_Number as d_Son_Height_Num, d.Son_Weight as
d_Son_Weight, ba.Height as ba_Height, ba.Weight as ba_Weight,
ba.Son_Height_Number as ba_Son_Height_Num, ba.Son_Weight as
ba_Son_Weight
from deleted d
inner join no.Man ba
on d.Height = ba.Son_Height_Number and d.Weight = ba.Son_Weight
)
Update no.Man
set Son_Height_Number = NULL, Son_Weight = NULL
from BA_DEL_Join
where d_Height = ba_Son_Height_Num and d_Weight = ba_Son_Weight
Go
Even though this code mimics a cascading event - it does not enfore referential integrity.

Related

SQL Server error: introducing foreign key constraint on table may cause cycles or multiple cascade paths

I have two tables, User and Data. For audit purposes, I have two columns added in the Datatable:AddedByandLastModifiedBy`.
Both columns reference the User table and its UserId column. I have a On delete set null constraint set on both the foreign keys. SQL Server does not let me create the table Data and throws the error:
Introducing FOREIGN KEY constraint 'FK__Data__LastModifi__0A9D95DB' on table 'Data' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
These are the SQL scripts:
CREATE TABLE [User]
(
UserId int PRIMARY KEY IDENTITY(1,1),
Name varchar(100) not null
)
CREATE TABLE [Data]
(
Id int PRIMARY KEY IDENTITY(1,1),
A int,
B varchar(10),
AddedBy int
FOREIGN KEY REFERENCES [User](UserId)
ON DELETE SET NULL,
LastModifiedBy int
FOREIGN KEY REFERENCES [User](UserId)
ON DELETE SET NULL
)
Removing the ON DELETE constraint solves the problem, but the question why can't I have two ON DELETE SET NULL conditions?
why can't I have two ON DELETE SET NULL conditions?
Because that would cause multiple cascade paths, and SQL Server simply doesn't support that.
There's an outstanding feedback request for this and to allow cascading in parent-child relationships here.
As a workaround you can either make one of the relationships ON DELETE NO ACTION, or use an INSTEAD OF DELETE trigger on USER that handles the cascading behavior.

Update even though using constraints

I'm trying to update a value (small spelling error) in the SQL Server 2014 database.
I do like this:
update t_Table set funID = 'References' where funID = 'Referencies'
When doing this I get the error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_t_Table_Language_t_Table". The conflict occurred in database "db", table "dbo.t_Table".
If updating the foreign key, I get a similar error.
Is there any way to update all values at the same time?
I have a vague memory of someone showing a way to do this in management studio but I do not recall how.
Enable update cascade on the foreign key
ALTER TABLE t_Table_Language DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table_Language ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table(funID)
ON UPDATE CASCADE
EDIT:
Or the other way around, i'm not sure which table has the foreing key
ALTER TABLE t_Table DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table_Language(funID)
ON UPDATE CASCADE
Then do the update on the referenced table (the master table).
UPDATE t_Table_Language
SET funID = 'References'
WHERE funID = 'Referencies'

Error about CASCADE in Sql - Server 2008

I posted this problem yesterday and didn't get answer.
I attach here sample of my problem. I want to create this DB:
CREATE DATABASE [TRYShemen];
GO
USE [TRYShemen]
GO
CREATE TABLE Persons(
ID VARCHAR(50) PRIMARY KEY,
FullName VARCHAR(50) NOT NULL
);
CREATE TABLE Class(
ClassNum VARCHAR(30) PRIMARY KEY,
Teacher VARCHAR(50) NOT NULL,
constraint Class_FK foreign key (Teacher) references Persons (ID) ON DELETE NO ACTION ON UPDATE CASCADE,
);
CREATE TABLE Students(
StudentID VARCHAR(50) ,
ClassNum VARCHAR(30)
constraint Students_PK PRIMARY KEY (StudentID, ClassNum),
constraint Students_FK foreign key (StudentID) references Persons(ID) ON DELETE NO ACTION ON UPDATE CASCADE ,
constraint Students_FK1 foreign key (ClassNum) references Class(ClassNum) ON DELETE NO ACTION ON UPDATE CASCADE
);
and I get an error:
Introducing FOREIGN KEY constraint 'Students_FK1' on table 'Students' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I know that if i change the 'Students_FK1' to ON CASCADE NO ACTION, it will work, but it's not my target. I want that if the id of 'Person' will update , it will update in the Students table too.
how can I solve it?
Thank You!!
So what can you do about it?
Consider this structure as an alternative.
table-Persons
table-Students
table-Teachers
table-Classes
table-Classes_to_Teachers
table-Classes_to_Students
Then you can have Cascading references for
Persons-->Students & Students-->Classes_to_Students
Persons-->Teachers & Teachers-->Classes_to_Teachers
When you access your data, you will have more joins to get all the data for one class.
But the constraints should work out.
Note that it says "may cause cycles or multiple cascade paths." If you follow a delete action through your ER diagram, you'll probably find that the delete action cascades to the same table via multiple routes.
In this case, imagine that the same person is both the teacher and the student in a class. Yes, I know, that's a logic error, but if that condition were true, then an update to that person would cascade to the students table via two routes.

Do Foreign Key constraints get checked on an SQL update statement that doesn't update the columns with the Constraint?

Do Foreign Key constraints get checked on an SQL update statement that doesn't update the columns with the Constraint? (In MS SQL Server)
Say I have a couple of tables with the following columns:
OrderItems
- OrderItemID
- OrderItemTypeID (FK to a OrderItemTypeID column on another table called OrderItemTypes)
- ItemName
If I just update
update [dbo].[OrderItems]
set [ItemName] = 'Product 3'
where [OrderItemID] = 2508
Will the FK constraint do it's lookup/check with the update statement above? (even thought the update is not change the value of that column?)
No, the foreign key is not checked. This is pretty easy to see by examining the execution plans of two different updates.
create table a (
id int primary key
)
create table b (
id int,
fkid int
)
alter table b add foreign key (fkid) references a(id)
insert into a values (1)
insert into a values (2)
insert into b values (5,1) -- Seek on table a's PK
update b set id = 6 where id = 5 -- No seek on table a's PK
update b set fkid = 2 where id = 6 -- Seek on table a's PK
drop table b
drop table a
No. Since the SQL update isn't updating a column containing a constraint, what exactly would SQL Server be checking in this case? This is similar to asking, "does an insert trigger get fired if I only do an update?" Answer is no.
There is a case when the FK not existing will prevent updates to other columns even though the FK is not changed and that is when the FK is created WITH NOCHECK and thus not checked at the time of creation. Per Books Online:
If you do not want to verify new CHECK or FOREIGN KEY constraints
against existing data, use WITH NOCHECK. We do not recommend doing
this, except in rare cases. The new constraint will be evaluated in
all later data updates. Any constraint violations that are suppressed
by WITH NOCHECK when the constraint is added may cause future updates
to fail if they update rows with data that does not comply with the
constraint.

How do I use cascade delete with SQL Server?

I have 2 tables: T1 and T2, they are existing tables with data. We have a one to many relationship between T1 and T2. How do I alter the table definitions to perform cascading delete in SQL Server when a record from T1 is deleted, all associated records in T2 also deleted.
The foreign constraint is in place between them. I don't want to drop the tables or create a trigger to do the deletion for T2. For example, when I delete an employee, all the review record should be gone, too.
T1 - Employee,
Employee ID
Name
Status
T2 - Performance Reviews,
Employee ID - 2009 Review
Employee ID - 2010 Review
To add "Cascade delete" to an existing foreign key in SQL Server Management Studio:
First, select your Foreign Key, and open it's "DROP and Create To.." in a new Query window.
Then, just add ON DELETE CASCADE to the ADD CONSTRAINT command:
And hit the "Execute" button to run this query.
By the way, to get a list of your Foreign Keys, and see which ones have "Cascade delete" turned on, you can run this script:
SELECT
OBJECT_NAME(f.parent_object_id) AS 'Table name',
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS 'Field name',
delete_referential_action_desc AS 'On Delete'
FROM sys.foreign_keys AS f,
sys.foreign_key_columns AS fc,
sys.tables t
WHERE f.OBJECT_ID = fc.constraint_object_id
AND t.OBJECT_ID = fc.referenced_object_id
ORDER BY 1
And if you ever find that you can't DROP a particular table due to a Foreign Key constraint, but you can't work out which FK is causing the problem, then you can run this command:
sp_help 'TableName'
The SQL in that article lists all FKs which reference a particular table.
Hope all this helps.
Apologies for the long finger. I was just trying to make a point.
You will need to,
Drop the existing foreign key constraint,
Add a new one with the ON DELETE CASCADE setting enabled.
Something like:
ALTER TABLE dbo.T2
DROP CONSTRAINT FK_T1_T2 -- or whatever it's called
ALTER TABLE dbo.T2
ADD CONSTRAINT FK_T1_T2_Cascade
FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE
You can do this with SQL Server Management Studio.
→ Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.
Use something like
ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;
Fill in the correct column names and you should be set. As mark_s correctly stated, if you have already a foreign key constraint in place, you maybe need to delete the old one first and then create the new one.
ON DELETE CASCADE
It specifies that the child data is deleted when the parent data is deleted.
CREATE TABLE products
( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
ON DELETE CASCADE
);
For this foreign key, we have specified the ON DELETE CASCADE clause which tells SQL Server to delete the corresponding records in the child table when the data in the parent table is deleted. So in this example, if a product_id value is deleted from the products table, the corresponding records in the inventory table that use this product_id will also be deleted.
First To Enable ONCascade property:
1.Drop the existing foreign key constraint
2.add a new one with the ON DELETE CASCADE setting enabled
Ex:
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
BEGIN
ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]
ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request] FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END
ELSE
BEGIN
ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request] FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END
Second To Disable ONCascade property:
1.Drop the existing foreign key constraint
2.Add a new one with the ON DELETE NO ACTION setting enabled
Ex:
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
BEGIN
ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]
ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request] FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END
ELSE
BEGIN
ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request] FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE NO ACTION
END
If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.
I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.

Resources