LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

[点晴永久免费OA]删除所有的用户表,存储过程,游标的应用,动态SQL的使用

admin
2020年3月3日 2:6 本文热度 2250
--存储过程,删除某数据库中所有的用户表,游标的应用,动态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 --调用存储过程,删除所有用户表

该文章在 2020/3/3 2:06:07 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved