今闲来无事写些SQL,欢迎大家来拍砖~~~

今闲来无事,胡乱搞点SQL 
功能是删除用户创建的表、视图、存储过程
需要对哪个数据库操作,连接上直接F5运行,测试前注意备份哦 或建个测试库
大家有啥好意见,欢迎讨论~~~
------------------------------------------------------------------------
--delete all the tables、views、procedures of the database
/****** Object:  three procedures    Script Date: 08/25/2007 17:17:28 by Sunbird69(**) ******/
print '        before deleting'
select name as tablename,type,crdate from sysobjects where type='u'
select name as viewname,type,crdate from sysobjects where type='v'
select name as procedurename,type,crdate from sysobjects where type='p'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--delete all user tables
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'delalltables') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure delalltables
as
declare @st varchar(200),@tablename nvarchar(30),@it int,@tcountrows int
set @it=0
select @tcountrows=count(name) from sysobjects where type=''u''
print @tcountrows
while @it<@tcountrows
 begin
  select @tablename=name from sysobjects where name = (select top 1 name from sysobjects where type=''u'')
  set @st=''drop table ''+@tablename
  exec(@st)
  print @tablename
  set @it=@it+1
 end'
END
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--drop all views tables
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'delallviews') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure delallviews
as
declare @sv varchar(200),@viewname nvarchar(30),@iv int,@vcountrows int
set @iv=0
select @vcountrows=count(name) from sysobjects where type=''v''
print @vcountrows
while @iv<@vcountrows
 begin
  select @viewname=name from sysobjects where name = (select top 1 name from sysobjects where type=''v'')
  set @sv=''drop view ''+@viewname
  exec(@sv)
  print @viewname
  set @iv=@iv+1
 end'
END
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--drop all procedures
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'delallprocedures') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure delallprocedures
as
declare @sp varchar(200),@procedurename nvarchar(30),@ip int,@pcountrows int
set @ip=0
select @pcountrows=count(name) from sysobjects where type=''p''
print @pcountrows
while @ip<@pcountrows
 begin
  select @procedurename=name from sysobjects where name = (select top 1 name from sysobjects where type=''p'')
  set @sp=''drop procedure ''+@procedurename
  exec(@sp)
  print @procedurename
  set @ip=@ip+1
 end'
END
GO

--carry out
exec delalltables
exec delallviews
exec delallprocedures

print '        after deleting'
--check the result
select name as tablename,type,crdate from sysobjects where type='u'
select name as viewname,type,crdate from sysobjects where type='v'
select name as procedurename,type,crdate from sysobjects where type='p'

你可能感兴趣的:(sql)