記錄 DB2 環境下,通過編目遠程節點、數據庫別名,使用 LOAD FROM CURSOR 和 db2move COPY 實現跨實例表數據高效遷移的完整操作步驟。
# 遠程主機 $ db2 get dbm cfg | grep SVCENAME TCP/IP 服務名稱 (SVCENAME) = 60000
# 編目遠程節點 db2 catalog tcpip node node_106 remote 108.88.3.106 server 60000 # 編目遠程數據庫別名 db2 catalog db test as test106 at node node_106 # 刷新目錄緩存 db2 terminate
db2 list node directory db2 list db directory db2 connect to test106 user db2inst4 using db2inst4
# 表 TABLEA, TABLEB (schema DB2INST2) db2 "create table DB2INST2.TABLEA(id integer, name char(10), salary integer)" db2 "insert into DB2INST2.TABLEA values(1001,'SAM',10000)..." # 表 TABLEC, TABLED (schema FOO, 含主鍵/外鍵) db2 "create table FOO.TABLEC(id integer not null primary key, name char(10), salary integer)" db2 "create table FOO.TABLED(id integer, lastname char(10))" db2 "alter table FOO.TABLED add constraint EMP_LNAME foreign key (id) references FOO.TABLEC"
適用於單表、無需建表(目標表已存在)的場景。
# 連接目標庫 db2 connect to tank # 確保目標表存在 db2 "create table DB2INST1.MYTABLE(id integer, name char(10), salary integer)" # 聲明游標指向遠程查詢 db2 "declare mycur cursor database test106 user db2inst4 using db2inst4 for select id,name,salary from db2inst2.tableA" # 執行裝載 db2 "load from mycur of cursor insert into db2inst1.mytable" # 驗證 db2 "select * from db2inst1.mytable"
優點:語法簡單、流式傳輸、不落地中間文件。
缺點:需目標表預先建好、不支持 DDL 複製、外鍵約束需手動處理。
db2move 是 DB2 官方遷移工具,支持 DDL+數據、模式級、表級、分階段操作。
db2move <源DB> COPY
-sn | -tn <表列表> | -tf <表文件>
-co TARGET_DB <目標DB> user <用戶> using <密碼>
MODE [DDL_AND_LOAD | DDL_ONLY | LOAD_ONLY]
-u <源用戶> -p <源密碼>
db2move test106 COPY -tn "DB2INST2.TABLEA","FOO.TABLEC" \
-co TARGET_DB tank user db2inst1 using db2inst1 MODE "LOAD_ONLY" \
-u db2inst4 -p db2inst4
# tbname.txt 內容:
"DB2INST2"."TABLEA"
"FOO"."TABLEC"
db2move test106 COPY -tf tbname.txt \
-co TARGET_DB tank user db2inst1 using db2inst1 MODE "LOAD_ONLY" \
-u db2inst4 -p db2inst4
# 前置條件:源庫必須存在 SYSTOOLSPACE 表空間
db2move test106 COPY -sn DB2INST2,FOO \
-co TARGET_DB tank user db2inst1 using db2inst1 MODE "DDL_AND_LOAD" \
-u db2inst4 -p db2inst4
報錯處理:若提示 SYSTOOLSPACE doesn't exist,在源庫執行:
db2 "create tablespace SYSTOOLSPACE"
# 1. 僅建表結構
db2move test106 COPY -sn DB2INST2,FOO \
-co TARGET_DB tank user db2inst1 using db2inst1 MODE "DDL_ONLY" \
-u db2inst4 -p db2inst4
# 2. 僅裝載數據(需處理外鍵約束導致的 SET INTEGRITY 待檢查狀態)
db2move test106 COPY -tf tbname.txt \
-co TARGET_DB tank user db2inst1 using db2inst1 MODE "LOAD_ONLY" \
-u db2inst4 -p db2inst4
# 3. 檢查並激活約束
db2 "SET INTEGRITY FOR FOO.TABLEC, FOO.TABLED IMMEDIATE CHECKED"
db2move COPY -sn 依賴源庫該表空間存儲元數據,必須預先創建。LOAD_ONLY 會將目標表置於 SET INTEGRITY PENDING 狀態,必須手動 SET INTEGRITY ... IMMEDIATE CHECKED 才能查詢。"DB2INST2"."TABLEA")。DATAACCESS, LOAD, CREATETAB 權限。LOADTABLE.*.MSG 記錄裝載行數、錯誤、索引重建信息,必須檢查。| 場景 | 推薦方案 |
|---|---|
| 單表、目標表已存在、一次性同步 | LOAD FROM CURSOR |
| 多表、需複製 DDL、生產遷移 | db2move COPY -sn MODE DDL_AND_LOAD |
| 部分表、僅同步數據、定時增量 | db2move COPY -tf MODE LOAD_ONLY |
| 大表、需分階段、控制鎖表時間 | DDL_ONLY + LOAD_ONLY 分離 |
掌握 db2move 的多種模式組合,能應對從開發環境同步到生產災備構建的各類 DB2 數據遷移需求。