我想删除架构中的所有表和存储过程,有人知道如何执行此操作吗?如果可能的话,我想避免丢弃整个数据库。
答案 0 :(得分:6)
您可以使用一系列drop来迭代sysobjects表,并系统地删除您想要的所有对象。
declare tables cursor
for select name from sysobjects where type='U'
go
declare @name varchar(255)
open tables
fetch tables into @name
while (@@sqlstatus = 0)
begin
exec("drop table "+ @name)
fetch tables into @name
end
close tables
deallocate cursor tables
是的,这需要游标,它会有点慢,但它应该几乎擦干数据库。
更多信息:
答案 1 :(得分:0)
试试这个
USE ban_des_rsp1
go
IF OBJECT_ID('rspman.sp_eliminar_base') IS NOT NULL
BEGIN
DROP PROCEDURE rspman.sp_eliminar_base
IF OBJECT_ID('rspman.sp_eliminar_base') IS NOT NULL
PRINT '<<< FAILED DROPPING PROCEDURE rspman.sp_eliminar_base >>>'
ELSE
PRINT '<<< DROPPED PROCEDURE rspman.sp_eliminar_base >>>'
END
go
create proc rspman.sp_eliminar_base
as
declare @w_id int, @w_name varchar(255), @w_rowcount int, @w_sql varchar(2000)
select @w_id = 0
set rowcount 0
while (@w_id>=0)
begin
set rowcount 1
select @w_sql = 'alter table ' + object_name(tableid) + ' DROP CONSTRAINT ' + object_name(constrid)
from sysconstraints
select @w_rowcount = @@rowcount
if @w_rowcount<>1
begin
set @w_id = -1
end
else
begin
exec(@w_sql)
end
end
set rowcount 0
set @w_id = 0
while (@w_id>=0)
begin
set rowcount 1
select @w_id = id, @w_name =name
from sysobjects
where type = 'V'
and id > @w_id
order by id
select @w_rowcount = @@rowcount
set rowcount 0
if @w_rowcount<>1
set @w_id = -1
else
begin
if (@w_name like 'gen%' or @w_name like 'vis%' )
begin
select @w_sql = 'drop view ' + @w_name
exec(@w_sql)
end
end
end
set rowcount 0
set @w_id = 0
while (@w_id>=0)
begin
set rowcount 1
select @w_id = id, @w_name =name
from sysobjects
where type = 'U'
and id > @w_id
order by id
select @w_rowcount = @@rowcount
set rowcount 0
if @w_rowcount<>1
set @w_id = -1
else
begin
select @w_sql = 'drop table ' + @w_name
exec(@w_sql)
end
end
set rowcount 0
set @w_id = 0
while (@w_id>=0)
begin
set rowcount 1
select @w_id = id, @w_name =name
from sysobjects
where type = 'P'
and id > @w_id
order by id
select @w_rowcount = @@rowcount
set rowcount 0
if @w_rowcount<>1
set @w_id = -1
else
begin
if @w_name like 'pro%'
begin
select @w_sql = 'drop proc ' + @w_name
exec(@w_sql)
end
end
end
go
EXEC sp_procxmode 'rspman.sp_eliminar_base', 'unchained'
go
IF OBJECT_ID('rspman.sp_eliminar_base') IS NOT NULL
PRINT '<<< CREATED PROCEDURE rspman.sp_eliminar_base >>>'
ELSE
PRINT '<<< FAILED CREATING PROCEDURE rspman.sp_eliminar_base >>>'
go