Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Cascading delete without foreign keys?

Tags:

sql

database

I have the following tables:

Country: Country_ID, CountryName
Regions: Region_ID, RegionName, Country_ID
Areas: Area_ID, AreaName, RegionID

I am not using foreign keys and not planning to do so, all I wanna do now is to be able in one query in the tableAdapter of country table to delete Country and all related regions, areas...

How?

like image 615
Maen Avatar asked Apr 16 '09 08:04

Maen


4 Answers

In one query? I doubt you could.

But you could do it in a three:

delete from Areas where RegionID in (select Region_ID from Regions where Country_ID in (select Country_ID where CountryName='Somelandia'))
delete from Regions where Country_ID in (select Country_ID where CountryName='Somelandia')
delete from Country where CountryName = 'Somelandia'

That being said, I strongly recommend you reconsider using foreign key relationships and cascade delete for this purpose.

like image 78
Jon Limjap Avatar answered Sep 20 '22 18:09

Jon Limjap


Use transactions. Start a transaction, then use three DELETE statements, then COMMIT TRANSACTION statement.

like image 35
sharptooth Avatar answered Sep 22 '22 18:09

sharptooth


You could try a stored procedure along these lines:

create proc EraseCountry
(
    @countryid int
)
as

BEGIN TRY 
BEGIN TRANSACTION 

    delete areas
    from areas 
        inner join regions on areas.region_id = regions.region_id
    where regions.countryid = @countryid

    delete regions
    where countryid = @countryid

    delete country
    where countryid = @countryid

COMMIT TRAN 
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRAN 
END CATCH
GO
like image 28
edosoft Avatar answered Sep 22 '22 18:09

edosoft


You could use a trigger if your database supports it and then use a transaction inside the trigger. The trigger would execute whenever a region or area is deleted.

like image 32
jimiyash Avatar answered Sep 18 '22 18:09

jimiyash