问题
I want to drop all tables and stored procedures in a schema, anyone know how to do this? I'd like to avoid dropping the entire database if possible.
回答1:
You could iterate over the sysobjects table with a series of drops and systematically drop all the objects you want gone.
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
Yes that requires cursors and it's gonna be a bit slow but it should pretty much wipe the database clean.
- for tables you would need to have type='U' and use drop table in the loop
- for stored procesures you would have P or XP and use drop procedure in the loop
More information:
- the sysobjects table specification
- using cursors
回答2:
Try this
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
来源:https://stackoverflow.com/questions/4799673/sybase-how-do-i-drop-all-tables-and-stored-procs-if-possible