許多開發者在 DB2 Command Line Processor (CLP) 直接貼上換行的 SQL 時,會遇到語法錯誤。原因在於:DB2 CLP 預設以分號 ; 為語句結束符,且不支援隨意換行。若在語句中間按 Enter,CLP 會嘗試執行不完整的片段,導致失敗。
在每行結尾加上 \,告訴 CLP 「這行還沒結束」:
db2 "SELECT * \
FROM my_table \
WHERE id = 1"
db2 -t(推薦)加上 -t 參數啟用「分號終結符模式」,即可自由換行撰寫 SQL,最後以 ; 送出:
$ db2 -t
(c) Copyright IBM Corporation 1993,2002
Command Line Processor for DB2 Client 11.5.x
You can issue database manager commands and SQL statements from the command prompt.
For example:
db2 => connect to sample
db2 => bind sample.bnd
db2 => CONNECT TO mydb USER myuser USING mypass
db2 => EXPORT TO "/home/user/data.txt" OF DEL MODIFIED BY coldel0x09
db2 (cont.) => SELECT col1, col2, col3
db2 (cont.) => FROM my_schema.my_table
db2 (cont.) => WHERE create_date = '2024-01-01'
db2 (cont.) => ;
SQL3104N The Export utility is beginning to export data to file "/home/user/data.txt".
SQL3105N The Export utility has finished exporting "554848" rows.
Number of rows exported: 554848
db2 => QUIT
DB20000I The QUIT command completed successfully.
touch data.txtdb2 CONNECT TO dbname USER uid USING pwddb2 -t; 送出QUIT 離開| 參數 | 說明 |
|---|---|
OF DEL | 以逗號分隔的純文字格式 |
MODIFIED BY coldel0x09 | 改用 Tab (0x09) 做欄位分隔,避免資料含逗號衝突 |
MODIFIED BY nochardel | 不輸出字串引號 |
MODIFIED BY codepage=1208 | 指定 UTF-8 編碼 |
匯出的純文字檔可直接用 Oracle SQL*Loader、External Table 或 ETL 工具導入,流程相對簡單,不再贅述。
db2 -t 互動模式撰寫多行 SQL,結尾以 ; 送出,最不易出錯。MODIFIED BY 調整分隔符與編碼,減少後續清洗麻煩。