Skip to main content

Script to delete data from all child tables with where condition

-- exec SP_ClearData 'TableName', 'Where condition', 0


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(max), /* name of the table where rows are to be deleted */
@cCriteria nvarchar(max), /* criteria used to delete the rows required */
@iRowsAffected int OUTPUT /* number of records affected by the delete */
set nocount on

declare @cTab varchar(max), /* name of the child table */
@cCol varchar(max), /* name of the linking field on the child table */
@cRefTab varchar(max), /* name of the parent table */
@cRefCol varchar(max), /* name of the linking field in the parent table */
@cFKName varchar(max), /* name of the foreign key */
@cSQL nvarchar(max), /* query string passed to the sp_ExecuteSQL procedure */
@cChildCriteria nvarchar(max), /* 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 */
SELECT AS Tab, AS Col, AS RefTab, AS RefCol, AS FKName
FROM dbo.sysforeignkeys FK
INNER JOIN dbo.syscolumns SC1 ON FK.fkeyid =
AND FK.fkey = SC1.colid
INNER JOIN dbo.syscolumns SC2 ON FK.rkeyid =
AND FK.rkey = SC2.colid
INNER JOIN dbo.sysobjects SO1 ON FK.fkeyid =
INNER JOIN dbo.sysobjects SO2 ON FK.rkeyid =
INNER JOIN dbo.sysobjects FO ON FK.constid =
WHERE SO2.Name = @cTableName
and <>

FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
/* 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 SP_ClearData @cTab, @cChildCriteria, @iChildRows OUTPUT
FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
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