Heim  >  Artikel  >  Datenbank  >  sql删除数据库中所有表与数据语句

sql删除数据库中所有表与数据语句

WBOY
WBOYOriginal
2016-06-07 15:00:062617Durchsuche

如果要删除数据表中所有数据只要遍历一下数据库再删除就可以了,清除所有数据我们可以使用搜索出所有表名,构造为一条SQL语句进行清除了,这里我一一给各位同学介绍。 使用sql删除数据库中所有表是不难的,就是遍历一下数据库中所有用户表,并将它清除,下边

如果要删除数据表中所有数据只要遍历一下数据库再删除就可以了,清除所有数据我们可以使用搜索出所有表名,构造为一条SQL语句进行清除了,这里我一一给各位同学介绍。

 

使用sql删除数据库中所有表是不难的,就是遍历一下数据库中所有用户表,并将它清除,下边是具体的sql语句,在关键部分已经作了详细的注释:

 代码如下 复制代码

--变量@tablename保存表名
declare @tablename nvarchar(100)

--将用户表全部保存到临时表#tablename中
SELECT [name] into #tablename FROM sysobjects
WHERE type = 'U';

--当#tablename有数据时
while(select count(1) from #tablename)>0
begin
--从#tablename中取第一条
select top 1 @tablename=[name] from #tablename;
--进行表删除操作,表名为变量,所以此处用到动态sql
exec('drop table '+@tablename);
--将此表名记录从#tablename中删除
delete from #tablename where [name]=@tablename;
end

--最后删除临时表#tablename

drop table #tablename可见sql里没有使用游标,而是使用了临时表用来遍历,到这里就达到了使用sql清除数据库中所有表的目的。

另一种办法

方便删除数据库中所有的数据表,清空数据库,有些有约束,不能直接delete,需要先删除库中的约束,代码如下

 

 代码如下 复制代码
--删除所有约束 
DECLARE c1 cursor for 
select'alter table ['+ object_name(parent_obj)+'] drop constraint ['+name+']; ' 
from sysobjects 
where xtype ='F' 
open c1 
declare @c1 varchar(8000) 
fetch nextfrom c1 into@c1 
while(@@fetch_status=0) 
begin 
exec(@c1) 
fetch nextfrom c1 into@c1 
end 
close c1 
deallocate c1 
--删除数据库所有表 
declare @tname varchar(8000) 
set@tname='' 
select@tname=@tname+Name+','from sysobjects where xtype='U' 
select@tname='drop table '+ left(@tname,len(@tname)-1) 
exec(@tname)

然后清空数据库中的所有表: 
如果需要删除存储过程等只需要将上面的做如下修改就行了的where xtype='U' 改成 where xtype='P',drop table 改成 drop Procedure


附上清空数据表中所有数据


清空所有数据.找到了三种方法进行清空.使用的数据库为MS SQL SERVER.
1.搜索出所有表名,构造为一条SQL语句

 代码如下 复制代码

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.利用游标清理所有表

 代码如下 复制代码

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.利用微软未公开的存储过程

 

 代码如下 复制代码

exec sp_msforeachtable "truncate table ?"

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn