删除某个数据库下面的所有表

USE test
-- 删除所有的 (约束 F)
DECLARE @countF INT
SET @countF = (SELECT COUNT(*) FROM test.sys.objects WHERE type = 'F')
PRINT '一共有' + CAST(@countF AS VARCHAR(5)) + '个约束。'
WHILE @countF>0
BEGIN
DECLARE @F_Name VARCHAR(50)
DECLARE @tbName VARCHAR(50)
DECLARE @Cmd VARCHAR(100)
DECLARE @parent_Object_ID INT
SET @F_Name = (SELECT TOP(1) name FROM test.sys.objects
WHERE name IN ( SELECT t.name FROM test.sys.objects AS [t]) AND type='F'
)
SET @parent_Object_ID = (SELECT parent_object_id FROM test.sys.objects WHERE name=@F_Name)
SET @tbName = (SELECT name FROM test.sys.tables WHERE object_id=@parent_Object_ID)
SELECT @Cmd = 'ALTER TABLE ' + @tbName + ' DROP constraint ' + @F_Name
PRINT @Cmd
EXEC(@Cmd)

SET @countF=@countF-1
END

-- 删除所有的表
DECLARE @temp INT
SET @temp = (SELECT COUNT(*) FROM sys.tables)
PRINT '一共有' + CAST(@temp AS VARCHAR(20)) + '个表。'
WHILE @temp>0
BEGIN
DECLARE @tbName VARCHAR(50)
SET @tbName = ( SELECT TOP(1) name FROM sys.tables WHERE name in ( SELECT t.name FROM sys.tables AS [t] ) )
EXEC('DROP TABLE ' + @tbName)
PRINT '表:' + @tbName + '删除成功!'
SET @temp=@temp-1
END

posted @ 2015-03-11 14:46  amujcdd  阅读(320)  评论(0编辑  收藏  举报