核心管理指令
實例與連線控制
db2start # 啟動實例
db2stop force # 強制停止
db2 force application all # 強制斷開所有連線
db2 connect to <alias> user <uid> using <pwd> # 遠端連線測試
節點與資料庫編目
db2 list node directory # 查看節點目錄
db2 catalog tcpip node <node> remote <host> server <port> ostype <OS> # 編目 TCP/IP 節點
db2 uncatalog node <node> # 取消節點編目
db2 list database directory # 系統資料庫目錄
db2 list database directory on <磁碟> # 本地資料庫目錄
db2 catalog database <db> as <alias> at node <node> # 編目資料庫
db2 uncatalog database <db> # 取消資料庫編目
Schema 與代碼頁
set schema = <schema_name> # 設定當前 Schema
# 建庫指定字符集
create database <db> using codeset <codeset> territory <territory>
# 實例級代碼頁 (Windows 環境變數或 db2set)
db2set DB2CODEPAGE=1386
資料遷移與維護
版本升級遷移
# 低版本備份 → 高版本恢復 → 執行遷移
db2 migrate database <db_name>
DDL 匯出與腳本執行
db2look -d <db> -e -c -o <file> # 匯出表結構 DDL
db2 -tvf <file> # 執行 SQL 腳本
資料匯出/匯入
export to <file> of ixf select * from <table> # 匯出 IXF
import from <file> of ixf insert into <table> # 匯入 (insert/replace/create)
db2move <db> export -sn <schema> -u <uid> -p <pwd> # 異構遷移匯出
db2move <db> import # 異構遷移匯入
效能監控與調優
鎖與死鎖分析
db2 update monitor switches using lock on
db2 get snapshot for locks on <db>
緩衝池管理
create bufferpool <name> size <pages> [pagesize 4096]
alter bufferpool <name> size <pages>
drop bufferpool <name>
# size=-1 時由 buffpage 參數決定
統計資訊與執行計劃
runstats on table <schema>.<table> with distribution and detailed indexes all
reorgchk update statistics on table user
db2expln -d <db> -f <sql_file> -z ";" -g -o <out> # 靜態 SQL 計劃
db2advis -d <db> -i <sql_file> # 索引建議
資料庫一致性檢查
db2dart <db> /DB # 整庫一致性檢查
db2batch -d <db> -f <sql> # SQL 效能測試
常用查詢語句
describe table <table> # 檢視表結構
select * from syscat.procedures # 檢視預存程序
select * from syscat.checks where tabname=<t> # 檢視 CHECK 約束
select * from syscat.references where tabname=<t> # 檢視 FK 約束
select * from syscat.bufferpools # 緩衝池狀態
select * from sysibm.sysversions # DB2 版本資訊
進階技巧
- 多欄位 IN 查詢:
where (colA, colB) in (values (v1,v2), (v3,v4))
- 快速清空大表:
alter table <t> activate not logged initially with empty table
- 引號識別符查詢:
select * from "schema"."table"
- 配置參數調整:
db2 get/update dbm cfg、db2 get/update db cfg for <db>