How to delete all rows from all tables in a SQL Server database?

前端 未结 11 1196
遇见更好的自我
遇见更好的自我 2020-11-29 15:12

How to delete all rows from all tables in a SQL Server database?

11条回答
  •  没有蜡笔的小新
    2020-11-29 15:39

    This answer builds on Zach Smith's answer by resetting the identity column as well:

    1. Disabling all constraints
    2. Iterating through all tables except those you choose to exclude
    3. Deletes all rows from the table
    4. Resets the identity column if one exists
    5. Re-enables all constraints

    Here is the query:

    -- Disable all constraints in the database
    EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
    declare @catalog nvarchar(250);
    declare @schema nvarchar(250);
    declare @tbl nvarchar(250);
    DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
                                            TABLE_CATALOG,
                                            TABLE_SCHEMA,
                                            TABLE_NAME
                                            from INFORMATION_SCHEMA.TABLES
                                            where
                                            TABLE_TYPE = 'BASE TABLE'
                                            AND TABLE_NAME != 'sysdiagrams'
                                            AND TABLE_NAME != '__RefactorLog'
                                            -- Optional
                                            -- AND (TABLE_SCHEMA = 'dbo')
    
    OPEN i;
    FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
            /* Make sure these are the commands you want to execute before executing */
            PRINT 'Executing statement: ' + @sql
            --EXECUTE sp_executesql @sql
    
            -- Reset identity counter if one exists
            IF ((SELECT OBJECTPROPERTY( OBJECT_ID(@catalog + '.' + @schema + '.' + @tbl), 'TableHasIdentity')) = 1)
            BEGIN
                SET @sql = N'DBCC CHECKIDENT ([' + @catalog + '.' + @schema + '.' + @tbl + '], RESEED, 0)'
                PRINT 'Executing statement: ' + @sql
                --EXECUTE sp_executesql @sql
            END     
    
            FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
        END
    CLOSE i;
    DEALLOCATE i;
    
    -- Re-enable all constraints again
    EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
    

提交回复
热议问题