Performing a Cascade Delete in SQL Server 7

By Guest Authors on 4 April 2002 | Tags: DELETEs


This article comes to us from Tim Young. Tim writes "One of the (few) very handy things about Access is the cascade delete function. If you delete a record from a parent table, all relating records in the child tables are also deleted. I couldn’t find any way of doing this in SQL Server 7, so I wrote a stored procedure for it." Thanks for the article Tim!

Normally, if you try and delete a record from a table that is constrained by a foreign key, you’ll get an error message. This procedure checks for any foreign keys for the table, deletes any child records, then deletes the intended record.

It references the system tables sysforeignkeys, sysobjects and syscolumns. Sysforeignkeys does what it says on the tin – it’s a list of all foreign keys in the database. It doesn’t contain actual table and field names, instead it contains links to the sysobjects (tables, stored procedures, views etc) and syscolumns (fields).

The procedure works like this – if we want to delete a record from table X, we look in the sysforeignkeys table for all references where table X is the parent table. It may be involved in several such FK’s. All we do is recursively go through these FK’s, deleting the child table records that are linked to the record we want to delete.

For example,

- delete all records from table X where field1 equals '234'

    DELETE FROM X WHERE field1 = '234'

- table Y is linked to X through the Y_ID field, so

    DELETE FROM Y WHERE Y_ID IN (SELECT Y_ID FROM X WHERE field1 = '234')

- table Z is linked to Y through the Z_ref field

    DELETE FROM Z WHERE Z-ref IN 
        (SELECT Z_ref FROM Y WHERE Y_ID IN 
            (SELECT Y_ID FROM X WHERE field1 = '234'))

As you can see from the above example, if one of the child tables is also involved in a FK constraint, we also need to delete the relating rows in it’s child tables.

Here’s the code for the procedure:

CREATE Procedure spDeleteRows
/* 
Recursive row delete procedure. 

It deletes all rows in the table specified that conform to the criteria selected, 
while also deleting any child/grandchild records and so on.  This is designed to do the 
same sort of thing as Access's cascade delete function. It first reads the sysforeignkeys 
table to find any child tables, then deletes the soon-to-be orphan records from them using 
recursive calls to this procedure. Once all child records are gone, the rows are deleted 
from the selected table.   It is designed at this time to be run at the command line. It could 
also be used in code, but the printed output will not be available.
*/
	(
	@cTableName varchar(50), /* name of the table where rows are to be deleted */
	@cCriteria nvarchar(1000), /* criteria used to delete the rows required */
	@iRowsAffected int OUTPUT /* number of records affected by the delete */
	)
As
set nocount on
declare 	@cTab varchar(255), /* name of the child table */
	@cCol varchar(255), /* name of the linking field on the child table */
	@cRefTab varchar(255), /* name of the parent table */
	@cRefCol varchar(255), /* name of the linking field in the parent table */
	@cFKName varchar(255), /* name of the foreign key */
	@cSQL nvarchar(1000), /* query string passed to the sp_ExecuteSQL procedure */
	@cChildCriteria nvarchar(1000), /* criteria to be used to delete 
                                           records from the child table */
	@iChildRows int /* number of rows deleted from the child table */

/* declare the cursor containing the foreign key constraint information */
DECLARE cFKey CURSOR LOCAL FOR 
SELECT SO1.name AS Tab, 
       SC1.name AS Col, 
       SO2.name AS RefTab, 
       SC2.name AS RefCol, 
       FO.name AS FKName
FROM dbo.sysforeignkeys FK  
INNER JOIN dbo.syscolumns SC1 ON FK.fkeyid = SC1.id 
                              AND FK.fkey = SC1.colid 
INNER JOIN dbo.syscolumns SC2 ON FK.rkeyid = SC2.id 
                              AND FK.rkey = SC2.colid 
INNER JOIN dbo.sysobjects SO1 ON FK.fkeyid = SO1.id 
INNER JOIN dbo.sysobjects SO2 ON FK.rkeyid = SO2.id 
INNER JOIN dbo.sysobjects FO ON FK.constid = FO.id
WHERE SO2.Name = @cTableName

OPEN cFKey
FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
WHILE @@FETCH_STATUS = 0
     BEGIN
	/* build the criteria to delete rows from the child table. As it uses the 
           criteria passed to this procedure, it gets progressively larger with 
           recursive calls */
	SET @cChildCriteria = @cCol + ' in (SELECT [' + @cRefCol + '] FROM [' + 
                              @cRefTab +'] WHERE ' + @cCriteria + ')'
	print 'Deleting records from table ' + @cTab
	/* call this procedure to delete the child rows */
	EXEC spDeleteRows @cTab, @cChildCriteria, @iChildRows OUTPUT
	FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
     END
Close cFKey
DeAllocate cFKey
/* finally delete the rows from this table and display the rows affected  */
SET @cSQL = 'DELETE FROM [' + @cTableName + '] WHERE ' + @cCriteria
print @cSQL
EXEC sp_ExecuteSQL @cSQL
print 'Deleted ' + CONVERT(varchar, @@ROWCOUNT) + ' records from table ' + @cTableName

(Code sample generated at http://www.MarkItUp.com)

In the above scenario, we were trying to perform the following :

    DELETE FROM X WHERE field1 = '234'

Using this procedure, we would use the following command:

    exec spDeleteRows 'X', 'field1 = ''234''', 0

I hope this procedure has been of use. If you have any comments on it, please contact me.


- Advertisement -