SQL中删除所有约束、表、视图等脚本

作者:袖梨 2022-06-29

--删除所有约束、表、视图等SQL脚本

--###############################################
--删除所有外键约束
--###############################################

 代码如下 复制代码
DECLARE @SQL VARCHAR(99)
DECLARE CUR_CONSTRAINT CURSOR LOCAL FOR
 SELECT
  'ALTER TABLE '+
  CASE WHEN O.schema_id IS NOT NULL THEN (SELECT NAME+'.' FROM sys.schemas WHERE schema_id = O.schema_id) ELSE '' END
  +OBJECT_NAME(parent_object_id)+' DROP CONSTRAINT '+OBJECT_NAME(object_id)
 FROM sys.objects AS O JOIN sys.schemas AS S on O.schema_id=S.schema_id
 WHERE O.type IN('C','D','F')
OPEN CUR_CONSTRAINT
FETCH CUR_CONSTRAINT INTO @SQL
WHILE @@FETCH_STATUS =0
 BEGIN
  EXEC(@SQL)
  FETCH CUR_CONSTRAINT INTO @SQL
 END
CLOSE CUR_CONSTRAINT
DEALLOCATE CUR_CONSTRAINT

--###############################################
--删除所有视图(存储过程、函数等用同样的方法)
--###############################################
--DECLARE @SQL VARCHAR(99)

 代码如下 复制代码
DECLARE CUR_VIEW CURSOR LOCAL FOR
 SELECT
  'IF OBJECT_ID('''+
  CASE WHEN O.schema_id IS NOT NULL THEN (SELECT NAME+'.' FROM sys.schemas WHERE schema_id = O.schema_id) ELSE '' END
  +OBJECT_NAME(object_id)
  +''') IS NOT NULL'+
  +' DROP VIEW '+
  CASE WHEN O.schema_id IS NOT NULL THEN (SELECT NAME+'.' FROM sys.schemas WHERE schema_id = O.schema_id) ELSE '' END
  +OBJECT_NAME(object_id)
 FROM sys.objects AS O JOIN sys.schemas AS S on O.schema_id=S.schema_id
 WHERE O.type IN('V')
OPEN CUR_VIEW
FETCH CUR_VIEW INTO @SQL
WHILE @@FETCH_STATUS =0
 BEGIN
  EXEC(@SQL)
  FETCH CUR_VIEW INTO @SQL
 END
CLOSE CUR_VIEW
DEALLOCATE CUR_VIEW

--###############################################
-- 删除所有表
--###############################################

 代码如下 复制代码

--DECLARE @SQL VARCHAR(99)
DECLARE CUR_TABLE CURSOR LOCAL FOR
SELECT
 'DROP TABLE '+
  CASE WHEN O.schema_id IS NOT NULL THEN (SELECT NAME+'.' FROM sys.schemas WHERE schema_id = O.schema_id) ELSE '' END
  +O.name
FROM sys.objects AS O JOIN sys.schemas AS S on O.schema_id=S.schema_id
WHERE O.type='U'
OPEN CUR_TABLE
FETCH CUR_TABLE INTO @SQL
WHILE @@FETCH_STATUS =0
 BEGIN
  EXEC(@SQL)
  FETCH CUR_TABLE INTO @SQL
 END
CLOSE CUR_TABLE
DEALLOCATE CUR_TABLE

 

--###############################################

再提供一下SQL Server里的OBJECT_ID函数object_type参数类型

--###############################################

OBJECT_ID(object_name,object_type)
对象类型:
AF =聚合函数(CLR
C = CHECK约束
D = DEFAULT(约束或独立)
F = FOREIGN KEY约束
FN = SQL标量函数
FS =大会(CLR)的标量函数
FT =程序集(CLR)表值函数
IF = SQL内联表值函数
IT =内部表
P = SQL存储过程
电脑大会(CLR)存储过程
PG =计划指南
PK = PRIMARY KEY约束
R =规则(旧式,单机)
RF =复制过滤过程
S =系统基表
SN =同义词
SQ =服务队列
TA =组件(CLR)DML触发器
TF = SQL表值函数
TR = SQL DML触发器
TT =表类型
U =表(用户定义)
UQ = UNIQUE约束
V =视图
X =扩展存储过程

 

相关文章

精彩推荐