HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

TSQL: How to DELETE in cascade without altering table / indexes

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withouttsqldeletetableindexescascadehowaltering

Problem

I have inserted some data in a table where I should not have. I am trying to delete the data, but it has a 1:M relationship and I need to also delete data that references this one.

I do not want to alter the tables / indexes, I just need this instruction to cascade:

-- this alters the CONSTRAINT -- not an option:
ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;


Also I would like (read - prefer) not to change the IDE GUI settings.

Solution

Perhaps simply do it manually with two deletes, in a transaction to ensure consistency:

BEGIN TRANSACTION
DELETE T2 WHERE employeeID IN (SELECT employeeID FROM T1 WHERE 
DELETE T1 WHERE 
COMMIT TRANSACTION


You might want to add that FK constraint anyway, with or without the cascade options (I very much prefer without cascade, so still needing the manually ordered deletes, it is very convenient in some cases but adds dangers...), if it is correct for your data model.

Code Snippets

BEGIN TRANSACTION
DELETE T2 WHERE employeeID IN (SELECT employeeID FROM T1 WHERE <clauses_to_find_the_records_to_delete>
DELETE T1 WHERE <clauses_to_find_the_records_to_delete>
COMMIT TRANSACTION

Context

StackExchange Database Administrators Q#174550, answer score: 12

Revisions (0)

No revisions yet.