sql server 删除所有的表

时间:2021-11-23 06:42:31

--/第1步**********删除所有表的外键约束*************************/
DECLARE c1 CURSOR FOR
  SELECT ‘alter table [‘ Object_name(parent_obj)
         ‘] drop constraint [‘ name ‘]; ‘
  FROM   sysobjects
  WHERE  xtype = ‘F‘

OPEN c1

DECLARE @c1 VARCHAR(8000)

FETCH next FROM c1 INTO @c1

WHILE( @@FETCH_STATUS = 0 )
  BEGIN
      EXEC(@c1)

      FETCH next FROM c1 INTO @c1
  END

CLOSE c1

DEALLOCATE c1

--/第2步**********删除所有表*************************/
DECLARE @sql VARCHAR(8000)

WHILE (SELECT Count(*)
       FROM   sysobjects
       WHERE  type = ‘U‘) > 0
  BEGIN
      SELECT @sql = ‘drop table ‘ name
      FROM   sysobjects
      WHERE  ( type = ‘U‘ )
      ORDER  BY ‘drop table ‘ name

      EXEC(@sql)
  END