刪除數據庫所有table的資料(二)

本文介绍如何使用SQL Server中的sp_MSforeachtable存储过程来批量执行SQL命令,包括禁用和启用外键约束、触发器、删除表数据、检查表信息等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用微軟未公開的存儲過程來執行


/*
1)說明
系統存儲過程sp_MSforeachtable和sp_MSforeachdb,是微軟提供的兩個不公開的存儲過程,從ms sql 6.5開始。
存放在SQL Server的MASTER資料庫中。 
2)參數說明:
@command1 nvarchar(2000),          --第一條運行的SQL指令
@replacechar nchar(1) = N'?',      --指定的占位元符號
@command2 nvarchar(2000)= null,    --第二條運行的SQL指令
@command3 nvarchar(2000)= null,    --第三條運行的SQL指令
@whereand nvarchar(2000)= null,    --可選條件來選擇表
@precommand nvarchar(2000)= null,  --執行指令前的操作(類似控制項的觸發前的操作)
@postcommand nvarchar(2000)= null  --執行指令後的操作(類似控制項的觸發後的操作) 


*/

exec sp_msforeachtable "alter table ? nocheck CONSTRAINT all"  --禁所有外鍵
exec sp_msforeachtable "alter table ? DISABLE  TRIGGER  all"  --禁所有觸發器

--刪除所有表的數據,有外鍵的除外
exec sp_msforeachtable @command1='truncate table ?'
,@whereand=' and  (objectproperty(o.id,''TableHasForeignRef'')=0 and  objectproperty(o.id,''TableHasForeignKey'')=0) ' 

--把有外鍵的數據刪除
exec sp_msforeachtable @command1='delete  ?'
,@whereand=' and  (objectproperty(o.id,''TableHasForeignRef'')=1 or  objectproperty(o.id,''TableHasForeignKey'')=1) ' 


--數據庫所有表的信息
exec sp_MSforeachtable @command1="sp_spaceused '?'"



exec sp_msforeachtable "alter table ? check CONSTRAINT all"  --開啟所有外鍵
exec sp_msforeachtable "alter table ? enable  TRIGGER  all"    --開啟所有觸發器

--所有 identity表復原為1的
exec sp_MSforeachtable @command1='dbcc checkident([?],reseed,0) ' ,@whereand= ' and  (objectproperty(o.id,''TableHasIdentity'')=1) ' 

--重建所有索引
exec sp_MSforeachtable @command1='dBCC DBREINDEX ([?]) '




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值