加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

清空数据库中所有表记录 记录ID恢复从0开始

发布时间:2020-12-12 09:31:15 所属栏目:MsSql教程 来源:网络整理
导读:1.搜索出所有表名,构造为一条SQL语句 div class="codetitle" a style="CURSOR: pointer" data="24889" class="copybut" id="copybut24889" onclick="doCopy('code24889')" 代码如下:div class="codebody" id="code24889" declare @trun_name varchar(8000) s

1.搜索出所有表名,构造为一条SQL语句
<div class="codetitle"><a style="CURSOR: pointer" data="24889" class="copybut" id="copybut24889" onclick="doCopy('code24889')"> 代码如下:<div class="codebody" id="code24889">
declare @trun_name varchar(8000)
set @trun_name=''
select @trun_name=@trun_name + 'truncate table ' + [name] + ' ' from sysobjects where xtype='U' and status > 0
exec (@trun_name)

该方法适合表不是非常多的情况,否则表数量过多,超过字符串的长度,不能进行完全清理.
2.利用游标清理所有表
<div class="codetitle"><a style="CURSOR: pointer" data="16603" class="copybut" id="copybut16603" onclick="doCopy('code16603')"> 代码如下:<div class="codebody" id="code16603">
declare @trun_name varchar(50)
declare name_cursor cursor for
select 'truncate table ' + name from sysobjects where xtype='U' and status > 0
open name_cursor
fetch next from name_cursor into @trun_name
while @@FETCH_STATUS = 0
begin
exec (@trun_name)
print 'truncated table ' + @trun_name
fetch next from name_cursor into @trun_name
end
close name_cursor
deallocate name_cursor

这是我自己构造的,可以做为存储过程调用,能够一次清空所有表的数据,并且还可以进行有选择的清空表.
3.利用微软未公开的存储过程
<div class="codetitle"><a style="CURSOR: pointer" data="94577" class="copybut" id="copybut94577" onclick="doCopy('code94577')"> 代码如下:<div class="codebody" id="code94577">
exec sp_msforeachtable "truncate table ?"

该方法可以一次清空所有表,但不能加过滤条件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读