Reputation: 3720
I am writing an SSIS package where in a SQL task, I have to delete a record from a table. This record is linked to some tables and these related tables may be related to some other tables. So when I attempt to delete a record, I should remove all the references of it in other tables first.
I know that setting Cascaded delete is the best option to achieve this. However, it’s a legacy database where this change is not allowed. Moreover, it’s a transactional database where any accidental deletes from the application should be avoided.
Is there any way that SQL Server offers to frame such cascaded delete queries? Or writing the list of deletes manually is the only option?
Upvotes: 0
Views: 458
Reputation: 65157
The way that SQL Server offers to frame cascaded deletes is to use ON DELETE CASCADE
which you have said you can't use.
It's possible to query to metadata to get a list of affected records in other tables, but it would be complicated since you want to remove the constraint (and therefore the metadata reference) before the delete.
You would need to, in a single transaction:
Query the metadata to get a list of affected tables. This would need to be recursive so you can get tables affected by the first tier, then those affected by those affected by the first tier, and so on.
Drop the constraint. This will also need to be recursive for the same reasons as listed above.
Delete the record(s) in all affected tables
Re-enable the constraints
Someone else may have a more elegant solution but I think this is probably it.
It could be easier to do in .NET with SQL Management Objects as well, if that's an option.
I should clarify too that I'm not endorsing this as the potential for issues is very very high.
I think your safest course of action is to manually write out the deletes.
Upvotes: 1