Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7798035
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T23:52:49+00:00 2026-06-01T23:52:49+00:00

Somebody must have already written a script to delete all lines from all tables

  • 0

Somebody must have already written a script to delete all lines from all tables of a database.
Using DELETE command is not an option since it can takes ages on large tables.
Of course there are many examples on stackoverflow and elsewhere, but they don’t work with tables using foreign keys.

Basically, the script should do this :

  • Store all foreign keys definition in a temporary table
  • delete all foreign keys
  • truncate all tables
  • restore foreign keys

I think i have it :

IF OBJECT_ID('tempdb..#ForeignKeys') IS NOT NULL
    DROP TABLE #ForeignKeys;

WITH ForeignKeys AS (
SELECT
    QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) AS ParentTable
    , QUOTENAME(SCHEMA_NAME(rt.schema_id)) + '.' + QUOTENAME(rt.name) AS ReferenceTable
    , QUOTENAME(f.name) AS ConstraintName
    , STUFF(Parent.Cols, 1, 1, '') AS ParentColumns
    , STUFF(Reference.Cols, 1, 1, '') AS ReferenceColumns
    , REPLACE(f.update_referential_action_desc, '_', ' ') AS UpdateAction
    , REPLACE(f.delete_referential_action_desc, '_', ' ') AS DeleteAction
FROM
    sys.tables AS t
    LEFT JOIN sys.foreign_keys AS f
        ON f.parent_object_id = t.object_id
        AND f.type = 'F'
    LEFT JOIN sys.tables AS rt
        ON f.referenced_object_id = rt.object_id
    CROSS APPLY
    (
        SELECT
            ',' + QUOTENAME(COL_NAME(fc.parent_object_id, fc.parent_column_id))AS [text()]
        FROM
            sys.foreign_key_columns AS fc
        WHERE
            fc.constraint_object_id = f.object_id
        ORDER BY
            fc.constraint_column_id
        FOR XML PATH('')
    ) Parent(Cols)
    CROSS APPLY
    (
        SELECT
            ',' + QUOTENAME(COL_NAME(fc.referenced_object_id, fc.referenced_column_id)) AS [text()]
        FROM
            sys.foreign_key_columns AS fc
        WHERE
            fc.constraint_object_id = f.object_id
        ORDER BY
            fc.constraint_column_id
        FOR XML PATH('')
    ) Reference(Cols)
)
SELECT
    ParentTable AS TableName
    , 'ALTER TABLE ' + ParentTable + ' DROP CONSTRAINT ' + ConstraintName  AS DropCmd
    , 'TRUNCATE TABLE ' + ParentTable AS TruncateCmd
    , 'ALTER TABLE ' + ParentTable + ' ADD CONSTRAINT ' + ConstraintName + ' FOREIGN KEY('
        +  ParentColumns + ') REFERENCES ' + ReferenceTable + ' (' + ReferenceColumns 
        + ') ON UPDATE ' + UpdateAction 
        + ' ON DELETE ' + DeleteAction  COLLATE SQL_Latin1_General_CP1_CI_AS AS CreateCmd
INTO
    #ForeignKeys
FROM
    ForeignKeys
ORDER BY
 1;

-- SELECT * FROM #ForeignKeys

DECLARE @TableName SYSNAME
DECLARE @Sql NVARCHAR(MAX)

-- Drop all constraints
DECLARE FkCursor CURSOR FOR 
SELECT
    TableName
    , DropCmd
FROM
    #ForeignKeys
WHERE
    DropCmd IS NOT NULL     

OPEN FkCursor  
FETCH NEXT FROM FkCursor INTO @TableName, @Sql
WHILE @@FETCH_STATUS = 0  
BEGIN  
    PRINT @TableName + ' : ' + @sql
    EXEC sp_executesql @Sql
    FETCH NEXT FROM FkCursor INTO @TableName, @Sql
END
CLOSE FkCursor
DEALLOCATE FkCursor

-- Truncate all tables
DECLARE FkCursor CURSOR FOR 
SELECT
    TableName
    , TruncateCmd
FROM
    #ForeignKeys     

OPEN FkCursor  

FETCH NEXT FROM FkCursor INTO @TableName, @Sql
WHILE @@FETCH_STATUS = 0  
BEGIN  
    PRINT @TableName + ' : ' + @sql
    EXEC sp_executesql @Sql
    FETCH NEXT FROM FkCursor INTO @TableName, @Sql
END
CLOSE FkCursor
DEALLOCATE FkCursor

-- Create all foreign keys
DECLARE FkCursor CURSOR FOR 
SELECT
    TableName
    , CreateCmd
FROM
    #ForeignKeys
WHERE
    CreateCmd IS NOT NULL      

OPEN FkCursor  
FETCH NEXT FROM FkCursor INTO @TableName, @Sql
WHILE @@FETCH_STATUS = 0  
BEGIN  
    PRINT @TableName + ' : ' + @sql
    EXEC sp_executesql @Sql
    FETCH NEXT FROM FkCursor INTO @TableName, @Sql
END
CLOSE FkCursor
DEALLOCATE FkCursor

DROP TABLE #ForeignKeys;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T23:52:50+00:00Added an answer on June 1, 2026 at 11:52 pm
    DECLARE @drop     nvarchar(max) = N'', 
            @truncate nvarchar(max) = N'', 
            @create   nvarchar(max) = N'';
    
    ;WITH x AS
    (
        SELECT id = f.[object_id],
          cname = QUOTENAME(f.name),
          ctable = QUOTENAME(OBJECT_SCHEMA_NAME(f.parent_object_id)) 
            + N'.' + QUOTENAME(OBJECT_NAME(f.parent_object_id)),
          ccol = QUOTENAME(COL_NAME(fc.parent_object_id,fc.parent_column_id)),
          rtable = QUOTENAME(OBJECT_SCHEMA_NAME(f.referenced_object_id))
            + N'.' + QUOTENAME(OBJECT_NAME(f.referenced_object_id)),
          rcol = QUOTENAME(COL_NAME(fc.referenced_object_id,fc.referenced_column_id)),
          ou = f.update_referential_action_desc COLLATE SQL_Latin1_General_CP1_CI_AS,
          od = f.delete_referential_action_desc COLLATE SQL_Latin1_General_CP1_CI_AS
        FROM sys.foreign_keys AS f
        INNER JOIN sys.foreign_key_columns AS fc
        ON f.[object_id] = fc.constraint_object_id
        -- where clause to leave out certain tables here
    ),
    y AS
    (
      SELECT 
        d = CHAR(13) + CHAR(10) + N'ALTER TABLE ' + ctable + N' DROP CONSTRAINT ' + cname + ';',
        c = CHAR(13) + CHAR(10) + N'ALTER TABLE ' + ctable + N' ADD CONSTRAINT ' + cname 
          + ' FOREIGN KEY (' + STUFF((SELECT N',' + ccol FROM x AS x2 
            WHERE x2.id = x.id FOR XML PATH(''),
            TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 1, N'')
          + N') REFERENCES ' + rtable + N'(' + STUFF((SELECT N',' + rcol FROM x AS x3 
            WHERE x3.id = x.id FOR XML PATH(''),
            TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 1, '') + N')'
        + CASE WHEN od <> N'NO_ACTION' THEN 
          ' ON DELETE ' + REPLACE(od, N'SET_', N'SET ') ELSE N'' END
        + CASE WHEN ou <> N'NO_ACTION' THEN 
          ' ON UPDATE ' + REPLACE(ou, N'SET_', N'SET ') ELSE N'' END
      FROM x
    )
    SELECT 
      @drop = @drop + d, 
      @create = @create + c
    FROM y GROUP BY d,c;
    
    SELECT @truncate = @truncate + CHAR(13) + CHAR(10) + N'TRUNCATE TABLE ' 
      + QUOTENAME(SCHEMA_NAME(schema_id)) + N'.' + QUOTENAME(name) + N';'
      FROM sys.tables
      -- where clause to leave out certain tables here
    ;
    
    -- use results to text. Note that for 200 tables you won't be able to
    -- manually inspect the entire script in Management Studio because it
    -- will only show a certain number of characters depending on settings.
    
    SELECT @drop;
    SELECT @truncate;
    SELECT @create;
    
    -- when you are happy, uncomment these:
    
    --EXEC sys.sp_executesql @drop;
    --EXEC sys.sp_executesql @truncate;
    --EXEC sys.sp_executesql @create;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the problem that I must read Integers from a database. The varibles
There must be somebody out there who solved that already. Imagine I have a
Somebody asked similar question not long ago. But nobody answered comprehensively. Assume I have:
Somebody must have come up with a solution for this by now. We are
I did a search for this question thinking that somebody must have asked it
I have script.sh that must be run as user2. However, this script can only
My website was infected by a trojan script. Somebody managed to create/upload a file
I have a fairly unique situation with Asp.Net. An admin user must create any
I'm new to infragistics. I have a database and a datalayer with entity framework
I have been unable to make a definitive choice and was hoping that somebody

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.