Technical Article

Use DELETE On Many Tables With Foreign Keys

,

When deleting data from many tables, foreign key constraints can force you to specifically order your DELETE commands. This can take tons of time, especially if you have many tables.  Here's a technique I use to delete data in the correct order during the restaging of test databases.

It makes use of the system stored procedure sp_MSdependencies which does the work of finding the hierarchy of table dependencies.

--A temp table will hold all user table names
--We use it in a cursor to empty out the tables.
--The tables are listed in a specific order based on their dependencies
--We empty them out from the bottom up, avoiding any FK constraints
--  You can enter any tables you want ignored after the NOT IN 

IF OBJECT_ID('tempdb..#tUser')IS NOT NULL
DROP TABLE tempdb.#tUser
CREATE TABLE #tUser (type int, oName varchar(517), owner  varchar(517), seq int)

INSERT #tUser EXEC sp_MSdependencies NULL, 3, NULL, NULL, 1

DECLARE tcursor CURSOR READ_ONLY FOR

SELECT oName
FROM #tUser
WHERE oName NOT IN 
(
'enter exceptions here'
)
ORDER BY seq DESC

DECLARE  @sName varchar(517) 

OPEN tcursor
FETCH 
FROM tcursor
INTO @sName

WHILE @@FETCH_STATUS = 0
BEGIN

--Display the name to check progress...
PRINTCHAR(13)+''+@sName
EXEC('DELETE FROM '+@sName)
FETCH NEXT FROM tcursor INTO @sName


END
CLOSE tcursor
DEALLOCATE tcursor

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating