SQL脚本完全清理数据库?

时间:2013-06-18 07:09:35

标签: sql

有人可以帮助编写一个可以删除所有表的SQL脚本,以及数据库中的所有数据吗?

我知道我可以DROP tableName但是我想要一个可以在任何数据库中工作并完全清理它的脚本。

注意:我不想删除数据库本身,只需清空所有表并删除所有表。

注意:如果重要的话,我正在使用SQL Server Compact Edition。

5 个答案:

答案 0 :(得分:1)

SQL Server中似乎有一个存储过程可用于删除数据库中的所有表,如下所示:

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

source

答案 1 :(得分:1)

答案 2 :(得分:1)

DROP数据库名称。用这个。这很有帮助

答案 3 :(得分:0)

删除所有表格

- 删除所有密钥

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

删除所有存储过程

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

删除所有视图

    declare @procName varchar(500)
    declare cur cursor
        for select [name] from sys.objects where type = 'v'
    open cur

    fetch next from cur into @procName
          while @@fetch_status = 0
          begin
                      exec('drop view ' + @procName)
                      fetch next from cur into @procName
          end
    close cur
    deallocate cur

删除所有功能

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop function ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

答案 4 :(得分:0)

尝试

    TRUNCATE DATABASE

我希望它有效