删除所有的用户表,存储过程,游标的应用,动态SQL的使用

来源:网络 责任编辑:栏目编辑 发表时间:2013-07-01 10:45 点击:

 

--存储过程,删除某数据库中所有的用户表,游标的应用,动态SQL的使用 

--思路:先删除所有的外键,再删除所有的表;以免外键的存在导致不能删表 

--sys.objects表中parent_object_id表示某对象所依附的对象的ID,如外键所在表的ID 

--sys.foreign_keys表中有所有外键的信息,也有parent_object_id属性 

create database test 

go 

use test 

 

go 

create proc dropAllUserTable as 

begin 

    --声明游标,获得外键的名字及其所在的表的对象ID, 

    --sys.objects中type in ['F','U']分别表示外键及用户表 

    declare cursorForeignKey cursor for  

        select [name], parent_object_id from sys.objects where [type]='F' 

    open cursorForeignKey 

    declare @fkName nvarchar(30), @objId int, @tn nvarchar(30) 

    --提取外键的名字及其所在的表的对象ID到变量@fkName, @objId中 

    fetch next from cursorForeignKey into @fkName, @objId 

    while @@fetch_status=0 --删除所有的外键 

    begin        

        select @tn=[name] from sys.objects where [object_id]= @objId 

        set @tn=quotename(@tn) 

        exec('alter table ' + @tn + ' drop constraint ' + @fkName) 

        fetch next from cursorForeignKey into @fkName, @objId 

    end 

    close cursorForeignKey 

    deallocate cursorForeignKey 

 

    declare cursorTableName cursor for  

        select [name] from sys.objects where type='U' 

    open cursorTableName     

     

    fetch next from cursorTableName into @tn     

    while @@fetch_status=0 --删除所有的表 

    begin 

        set @tn=quotename(@tn)       

        exec ('drop table ' + @tn) 

        fetch next from cursorTableName into @tn 

    end 

    close cursorTableName 

    deallocate cursorTableName 

end 

 

go 

--测试,a,b两表相互参照 

create table a(a int primary key, b int) 

create table b(a int primary key, b int references a(a)) 

alter table a add foreign key(b) references b(a) 

 

--drop table a,b --出错! 

 

exec dropAllUserTable --调用存储过程,删除所有用户表   

 

摘自 寻找快乐

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • sql常见面试题
      • SQL SERVER 2005性能之跟踪
      • SQL编程(一)
      • LINUX上RMAN自动备份脚本
      • sql server面试题
      • 如何将多个SQL查询统计结果一次显示出来
      • 浅谈SQL Server中的事务日志(三)----在简单恢复模式下日志的角色
      • sql server 列转行
      • SQL小技巧系列 --- 行转列合并
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1