我需要用脚本将一个数据库中的内容全删了,包括表、视图、存储过程、关系图、约束等等,但数据库本身不能删除,就是相当于把这个库清空了,请教高手该脚本该怎么写...

解决方案 »

  1.   

    select case when xtyp='U' then 'drop table ' when xtype='P' then 'drop proc '....
    +quoteName
    from sysobjects
    where
    xtype in(...)
    --生成语句执行
      

  2.   

    用语句先把数据库删除了,再用create语句重建一个.
      

  3.   

    drop database database_name
    gocreate database database_name
    go
      

  4.   

    --删除所有的表
    declare @tablename varchar(100)
    declare cur_t cursor for select name from sys.sysobjects where xtype='U' and uid=1
    open cur_t
    fetch next from cur_t into @tablename
    while(@@fetch_status=0)
       begin
          declare @sql_t varchar(1000)
          set @sql_t='drop table '+@tablename
          exec(@sql_t)
          fetch next from cur_t into @tablename
       end
    close cur_t
    deallocate cur_t--删除所有的用户定义函数
    declare @functionname varchar(100)
    declare cur_f cursor for select name from sys.sysobjects where xtype='FN' and uid=1
    open cur_f
    fetch next from cur_f into @functionname
    while(@@fetch_status=0)
       begin
          declare @sql_f varchar(1000)
          set @sql_f='drop function '+@functionname
          exec(@sql_f)
          fetch next from cur_f into @functionname
       end
    close cur_f
    deallocate cur_f--删除所有的视图
    declare @viewname varchar(100)
    declare cur_v cursor for select name from sys.sysobjects where xtype='V' and uid=1
    open cur_v
    fetch next from cur_v into @viewname
    while(@@fetch_status=0)
       begin
          declare @sql_v varchar(1000)
          set @sql_v='drop view '+@viewname
          exec(@sql_v)
          fetch next from cur_v into @viewname
       end
    close cur_v
    deallocate cur_v--删除所有的存储过程,确保你的自定义的存储过程中不包含这样的名称"sp_名称"
    declare @procname varchar(100)
    declare cur_p cursor for select name from sys.sysobjects where xtype='p' and uid=1 and name not like 'sp_%'
    open cur_p
    fetch next from cur_p into @procname
    while(@@fetch_status=0)
       begin
          declare @sql_p varchar(1000)
          set @sql_p='drop view '+@procname
          exec(@sql_p)
          fetch next from cur_p into @procname
       end
    close cur_p
    deallocate cur_p