自己的系统中要调用外部的数据库,外部数据库庞大、而且其中许多表都是安全数据。
因为系统需要测试,为了做演示(Demo版本),除指定一部分表之外,把不需要用到的表全都删除。
/*
除指定表之外,清空数据库所有用户表.
*/
create procedure prc_deltb_except_specify (@specify_tbnames varchar(200))
as
begin
declare @s_tbname nvarchar(50),
@s_temp int,
@tmp_cnt int,
@sql nvarchar(100)
--游标 [查询所有的用户表]
declare cur_q cursor for
SELECT name FROM sysobjects WHERE (xtype = 'u') AND (status > 0)
set @s_temp = 0
open cur_q
fetch next from cur_q into @s_tbname
while @@fetch_status = 0
begin
set @s_temp = @s_temp + 1
print @s_tbname + '------' + convert(varchar(10),@s_temp) --打印表名
--delete表,排除指定表
select @tmp_cnt = count(a) FROM dbo.f_split(@specify_tbnames,',') where a = @s_tbname
if(@tmp_cnt<=0)
begin
set @sql = N'delete from '+ @s_tbname
exec sp_executesql @sql
print '已清空 : '+@s_tbname
end
fetch next from cur_q into @s_tbname
end
close cur_q
deallocate cur_q
end
/*
Split函数
用法: select * from dbo.f_split('A:B:C:D:E',':')
*/
create function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10))
returns @temp table(a varchar(100))
--实现split功能 的函数
--date :2005-4-20
--Author :Domino
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>'/'
insert @temp values(@SourceSql)
return
end
疑问:删除(delete)表时,有约束的表会删不掉。多执行几次才能删除(delete清空)掉。
如何删除数据库用户表之前删除所有的约束.
这篇博客介绍了如何在SQL Server中创建一个存储过程,用于清空所有用户表,但排除指定的一组表。首先定义了一个游标遍历所有用户表,然后使用一个自定义的split函数检查表名是否在排除列表中。如果不在,就执行删除操作。博主提到了当表有约束时删除操作可能会失败,并询问了如何在删除前解除表的约束。
2128

被折叠的 条评论
为什么被折叠?



