如何删除db2中的所有表

时间:2011-11-24 08:20:15

标签: sql db2 sql-drop

我想使用外键删除db2数据库中的所有表,而不删除和重新创建。

3 个答案:

答案 0 :(得分:5)

如果您还想删除所有视图,索引,外键等:

select 'drop index "' || TRIM(INDSCHEMA) || '"."' || TRIM(INDNAME) || '";'
  from SYSCAT.INDEXES
  where UNIQUERULE = 'D'
  and INDSCHEMA = (select current schema from SYSIBM.SYSDUMMY1);

select 'alter table "' || TRIM(TABSCHEMA) || '"."' || TRIM(TABNAME) || '" drop foreign key "' || TRIM(CONSTNAME) || '";'
  from SYSCAT.TABCONST
  where TYPE = 'F'
  and TABSCHEMA = (select current schema from SYSIBM.SYSDUMMY1)

select 'alter table "' || TRIM(TABSCHEMA) || '"."' || TRIM(TABNAME) || '" drop unique "' || TRIM(INDNAME) || '";'
  from SYSCAT.INDEXES
  where UNIQUERULE = 'U'
  and INDSCHEMA = (select current schema from SYSIBM.SYSDUMMY1);

select 'alter table "' || TRIM(TABSCHEMA) || '"."' || TRIM(TABNAME) || '" drop primary key;'
  from SYSCAT.INDEXES
  where UNIQUERULE = 'P'
  and INDSCHEMA = (select current schema from SYSIBM.SYSDUMMY1);

select 'drop table "' || TRIM(TABSCHEMA) || '"."' || TRIM(TABNAME) || '";'
  from SYSCAT.TABLES
  where TYPE = 'T'
  and TABSCHEMA = (select current schema from SYSIBM.SYSDUMMY1);

select 'drop view "' || TRIM(TABSCHEMA) || '"."' || TRIM(TABNAME) || '";'
  from SYSCAT.TABLES
  where TYPE = 'V'
  and TABSCHEMA = (select current schema from SYSIBM.SYSDUMMY1);

答案 1 :(得分:3)

如果你在Linux或Unix环境中。

#!/bin/ksh

## load profile of your instance owner

db2 "connect to <db_name">
db2 -x "select tabschema,tabname from syscat.tables where type='T' and tabschema not like 'SYS%' with ur"|while read a b

do
   db2 "load from /dev/null of del replace into $a.$b nonrecoverable"
done

return 0

此脚本将数据删除到表中。

答案 2 :(得分:1)

db2 "Select 'DROP TABLE ', tabname, ';' from syscat.tables where owner='DBUSER'" >> filename

删除文件的第一行和最后一行,然后使用

运行它
db2 -tvf filename.

这样我们也可以保存我们丢弃的表的日志。

PS:确保一次,只有你想要的表存在于文件中。不要错误地删除一些系统表。