Question

I have 30 tables in a database and all are related to each other via primary and foreign key relationships. The problem is that when I try to delete any record via a stored procedure, it doesn't delete because of the primary/foreign key relationship. What should I do in order to delete tables? Too many tables are interconnected.

ALTER PROCEDURE [dbo].[DeleteRegions_SP]

    @RegionID smallint

AS
BEGIN

    Begin Try

     Delete from Regions where RegionID = @RegionID  
    End Try
    Begin Catch
     Select ERROR_MESSAGE() as ErrorMessage
    End Catch
END
Was it helpful?

Solution

There are three ways SQL treats this quite normal situation:

ON DELETE CASCADE

which will delete the records that depend on the one you want to delete.

ON DELETE SET NULL 

which will set the FK field to NULL

and

ON DELETE RESTRICT

which is the dafault you hit against.

TSQL can also do a

ON DELETE SET DEFAULT

which may also be useful.

There is not a single solution for you (Especially not CASCADE)!

You will have to decide for each FK what will be right clause!

Database design is an art..

This answer is about deleting records not tables; if you really want to delete tables you must first lift the FK relationsships that depend on them.

OTHER TIPS

You have to delete the tables that have a Foreign Key before you can delete the table with the Primary Key

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top