刪除全部約束、表、視圖等SQL腳本

--刪除全部約束、表、視圖等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 =擴展存儲過程
相關文章
相關標籤/搜索