热门标签 | HotTags
当前位置:  开发笔记 > 数据库 > 正文

sqlserver批量清理指定数据库内容方法

本文章介绍了关于sqlserver批量清理指定数据库内容方法,有需要的同学可以参考一下下哦。

本文章介绍了关于sqlserver批量清理指定数据库内容方法,有需要的同学可以参考一下下哦。

代码如下

--Remove all data from a database

SET NOCOUNT ON
--Tables to ignore
DECLARE @IgnoreTables
TABLE (TableName varchar(512))
INSERT INTO @IgnoreTables (TableName) VALUES ('sysdiagrams')
DECLARE @AllRelationshi
TABLE (ForeignKey varchar(512)
,TableName varchar(512)
,ColumnName varchar(512)
,ReferenceTableName varchar(512)
,ReferenceColumnName varchar(512)
,DeleteRule varchar(512))
INSERT INTO @AllRelationships
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName,
delete_referential_action_desc as DeleteRule
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id


DECLARE @TableOwner varchar(512)
DECLARE @TableName varchar(512)
DECLARE @ForeignKey varchar(512)
DECLARE @ColumnName varchar(512)
DECLARE @ReferenceTableName varchar(512)
DECLARE @ReferenceColumnName varchar(512)
DECLARE @DeleteRule varchar(512)


PRINT('Loop through all tables and switch all constraints to have a delete rule of CASCADE')
DECLARE DataBaseTables0
CURSOR FOR
SELECT SCHEMA_NAME(t.schema_id) AS schema_name, t.name AS table_name
FROM sys.tables AS t;

OPEN DataBaseTables0;

FETCH NEXT FROM DataBaseTables0
INTO @TableOwner,@TableName;

WHILE @@FETCH_STATUS = 0
BEGIN
IF (NOT EXISTS(SELECT TOP 1 1 FROM @IgnoreTables WHERE TableName = @TableName))
BEGIN
PRINT '['+@TableOwner+'].[' + @TableName + ']';

DECLARE DataBaseTableRelationships CURSOR FOR
SELECT ForeignKey, ColumnName, ReferenceTableName, ReferenceColumnName
FROM @AllRelationships
WHERE TableName = @TableName

OPEN DataBaseTableRelationships;
FETCH NEXT FROM DataBaseTableRelationships INTO @ForeignKey, @ColumnName, @ReferenceTableName, @ReferenceColumnName;

IF @@FETCH_STATUS <> 0
PRINT '=====> No Relationships' ;

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT '=====> switching delete rule on ' + @ForeignKey + ' to CASCADE';
BEGIN TRANSACTION
BEGIN TRY
EXEC('

ALTER TABLE ['+@TableOwner+'].[' + @TableName + ']
DROP CONSTRAINT '+@ForeignKey+';

ALTER TABLE ['+@TableOwner+'].[' + @TableName + '] ADD CONSTRAINT
'+@ForeignKey+' FOREIGN KEY
(
'+@ColumnName+'
) REFERENCES '+@ReferenceTableName+'
(
'+@ReferenceColumnName+'
) ON DELETE CASCADE;
');
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT '=====> can''t switch ' + @ForeignKey + ' to CASCADE, - ' +
CAST(ERROR_NUMBER() AS VARCHAR) + ' - ' + ERROR_MESSAGE();
ROLLBACK TRANSACTION
END CATCH;

FETCH NEXT FROM DataBaseTableRelationships INTO @ForeignKey, @ColumnName, @ReferenceTableName, @ReferenceColumnName;
END;

CLOSE DataBaseTableRelationships;
DEALLOCATE DataBaseTableRelationships;

END
PRINT '';
PRINT '';

FETCH NEXT FROM DataBaseTables0
INTO @TableOwner,@TableName;
END
CLOSE DataBaseTables0;
DEALLOCATE DataBaseTables0;

PRINT('Loop though each table and DELETE All data from the table')

DECLARE DataBaseTables1 CURSOR FOR
SELECT SCHEMA_NAME(t.schema_id) AS schema_name, t.name AS table_name
FROM sys.tables AS t;

OPEN DataBaseTables1;

FETCH NEXT FROM DataBaseTables1
INTO @TableOwner,@TableName;

WHILE @@FETCH_STATUS = 0
BEGIN
IF (NOT EXISTS(SELECT TOP 1 1 FROM @IgnoreTables WHERE TableName = @TableName))
BEGIN
PRINT '['+@TableOwner+'].[' + @TableName + ']';
PRINT '=====> deleting data from ['+@TableOwner+'].[' + @TableName + ']';
BEGIN TRY
EXEC('
DELETE FROM ['+@TableOwner+'].[' + @TableName + ']
DBCC CHECKIDENT ([' + @TableName + '], RESEED, 0)
');
END TRY
BEGIN CATCH
PRINT '=====> can''t FROM ['+@TableOwner+'].[' + @TableName + '], - ' +
CAST(ERROR_NUMBER() AS VARCHAR) + ' - ' + ERROR_MESSAGE();
END CATCH;
END

PRINT '';
PRINT '';

FETCH NEXT FROM DataBaseTables1
INTO @TableOwner,@TableName;
END
CLOSE DataBaseTables1;
DEALLOCATE DataBaseTables1;

PRINT('Loop through all tables and switch all constraints to have a delete rule they had at the beggining of the task')

DECLARE DataBaseTables2 CURSOR FOR
SELECT SCHEMA_NAME(t.schema_id) AS schema_name, t.name AS table_name
FROM sys.tables AS t;
OPEN DataBaseTables2;

FETCH NEXT FROM DataBaseTables2
INTO @TableOwner,@TableName;

WHILE @@FETCH_STATUS = 0
BEGIN

IF (NOT EXISTS(SELECT TOP 1 1 FROM @IgnoreTables WHERE TableName = @TableName))
BEGIN
PRINT '['+@TableOwner+'].[' + @TableName + ']';

DECLARE DataBaseTableRelationships CURSOR FOR
SELECT ForeignKey, ColumnName, ReferenceTableName, ReferenceColumnName, DeleteRule
FROM @AllRelationships
WHERE TableName = @TableName

OPEN DataBaseTableRelationships;
FETCH NEXT FROM DataBaseTableRelationships INTO @ForeignKey, @ColumnName, @ReferenceTableName, @ReferenceColumnName, @DeleteRule;

IF @@FETCH_STATUS <> 0
PRINT '=====> No Relationships' ;

WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @switchBackTo varchar(50) =
CASE
WHEN @DeleteRule = 'NO_ACTION' THEN 'NO ACTION'
WHEN @DeleteRule = 'CASCADE' THEN 'CASCADE'
WHEN @DeleteRule = 'SET_NULL' THEN 'SET NULL'
WHEN @DeleteRule = 'SET_DEFAULT' THEN 'SET DEFAULT'
END

PRINT '=====> switching delete rule on ' + @ForeignKey + ' to ' + @switchBackTo;

BEGIN TRANSACTION
BEGIN TRY
EXEC('

ALTER TABLE ['+@TableOwner+'].[' + @TableName + ']
DROP CONSTRAINT '+@ForeignKey+';

ALTER TABLE ['+@TableOwner+'].[' + @TableName + '] ADD CONSTRAINT
'+@ForeignKey+' FOREIGN KEY
(
'+@ColumnName+'
) REFERENCES '+@ReferenceTableName+'
(
'+@ReferenceColumnName+'
) ON DELETE '+@switchBackTo+'
');

COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT '=====> can''t change '+@ForeignKey + ' back to '+ @switchBackTo +', - ' +
CAST(ERROR_NUMBER() AS VARCHAR) + ' - ' + ERROR_MESSAGE();
ROLLBACK TRANSACTION
END CATCH;

FETCH NEXT FROM DataBaseTableRelationships
INTO @ForeignKey, @ColumnName, @ReferenceTableName, @ReferenceColumnName, @DeleteRule;
END;

CLOSE DataBaseTableRelationships;
DEALLOCATE DataBaseTableRelationships;

END
PRINT '';
PRINT '';

FETCH NEXT FROM DataBaseTables2
INTO @TableOwner,@TableName;
END
CLOSE DataBaseTables2;

DEALLOCATE DataBaseTables2;


推荐阅读
  • 本文详细介绍了如何使用libpq库与PostgreSQL后端建立连接。通过探讨PQconnectdb()函数的工作原理及其在实际应用中的使用方法,帮助读者理解并掌握建立高效、稳定的数据库连接的关键步骤。 ... [详细]
  • Windows服务与数据库交互问题解析
    本文探讨了在Windows 10(64位)环境下开发的Windows服务,旨在定期向本地MS SQL Server (v.11)插入记录。尽管服务已成功安装并运行,但记录并未正确插入。我们将详细分析可能的原因及解决方案。 ... [详细]
  • 数据库内核开发入门 | 搭建研发环境的初步指南
    本课程将带你从零开始,逐步掌握数据库内核开发的基础知识和实践技能,重点介绍如何搭建OceanBase的开发环境。 ... [详细]
  • 本文深入探讨 MyBatis 中动态 SQL 的使用方法,包括 if/where、trim 自定义字符串截取规则、choose 分支选择、封装查询和修改条件的 where/set 标签、批量处理的 foreach 标签以及内置参数和 bind 的用法。 ... [详细]
  • 使用C#开发SQL Server存储过程的指南
    本文介绍如何利用C#在SQL Server中创建存储过程,涵盖背景、步骤和应用场景,旨在帮助开发者更好地理解和应用这一技术。 ... [详细]
  • 本文探讨了适用于Spring Boot应用程序的Web版SQL管理工具,这些工具不仅支持H2数据库,还能够处理MySQL和Oracle等主流数据库的表结构修改。 ... [详细]
  • 本文详细介绍了如何通过多种编程语言(如PHP、JSP)实现网站与MySQL数据库的连接,包括创建数据库、表的基本操作,以及数据的读取和写入方法。 ... [详细]
  • 在当前众多持久层框架中,MyBatis(前身为iBatis)凭借其轻量级、易用性和对SQL的直接支持,成为许多开发者的首选。本文将详细探讨MyBatis的核心概念、设计理念及其优势。 ... [详细]
  • 在使用 DataGridView 时,如果在当前单元格中输入内容但光标未移开,点击保存按钮后,输入的内容可能无法保存。只有当光标离开单元格后,才能成功保存数据。本文将探讨如何通过调用 DataGridView 的内置方法解决此问题。 ... [详细]
  • 本文详细介绍了如何在 Linux 平台上安装和配置 PostgreSQL 数据库。通过访问官方资源并遵循特定的操作步骤,用户可以在不同发行版(如 Ubuntu 和 Red Hat)上顺利完成 PostgreSQL 的安装。 ... [详细]
  • 如何在PostgreSQL中查看数据表
    本文将指导您使用pgAdmin工具连接到PostgreSQL数据库,并展示如何浏览和查找其中的数据表。通过简单的步骤,您可以轻松访问所需的表结构和数据。 ... [详细]
  • 利用存储过程构建年度日历表的详细指南
    本文将介绍如何使用SQL存储过程创建一个完整的年度日历表。通过实例演示,帮助读者掌握存储过程的应用技巧,并提供详细的代码解析和执行步骤。 ... [详细]
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • 在使用SQL Server进行动态SQL查询时,如果遇到LIKE语句无法正确返回预期结果的情况,通常是因为参数传递方式不当。本文将详细探讨这一问题,并提供解决方案及相关的技术背景。 ... [详细]
  • 本文介绍如何通过创建替代插入触发器,使对视图的插入操作能够正确更新相关的基本表。涉及的表包括:飞机(Aircraft)、员工(Employee)和认证(Certification)。 ... [详细]
author-avatar
书友79805954
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有