Delete all data in SQL Server database

前端 未结 10 1093
粉色の甜心
粉色の甜心 2020-12-04 05:11

How I can delete all records from all tables of my database? Can I do it with one SQL command or I need for one SQL command per one table?

10条回答
  •  孤城傲影
    2020-12-04 06:03

    1. First you'll have to disable all the triggers :

      sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all';
      
    2. Run this script : (Taken from this post Thank you @SQLMenace)

      SET NOCOUNT ON
      GO
      
      SELECT 'USE [' + db_name() +']';
      ;WITH a AS 
      (
           SELECT 0 AS lvl, 
                  t.object_id AS tblID 
           FROM sys.TABLES t
           WHERE t.is_ms_shipped = 0
             AND t.object_id NOT IN (SELECT f.referenced_object_id 
                                     FROM sys.foreign_keys f)
      
           UNION ALL
      
           SELECT a.lvl + 1 AS lvl, 
                  f.referenced_object_id AS tblId
           FROM a
           INNER JOIN sys.foreign_keys f ON a.tblId = f.parent_object_id 
                                         AND a.tblID <> f.referenced_object_id
      )
      SELECT 
          'Delete from ['+ object_schema_name(tblID) + '].[' + object_name(tblId) + ']' 
      FROM a
      GROUP BY tblId 
      ORDER BY MAX(lvl),1
      

    This script will produce DELETE statements in proper order. starting from referenced tables then referencing ones

    1. Copy the DELETE FROM statements and run them once

    2. enable triggers

      sp_msforeachtable 'ALTER TABLE ? ENABLE TRIGGER all'
      
    3. Commit the changes :

      begin transaction
      commit;
      

提交回复
热议问题