0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Oracle DatabaseでCSV出力・CSV入力する

Posted at

概要

Oracle DatabseでCSV出力・CSV入力する方法を紹介します。なおこのCSVはRFC4180の仕様を満たすものとします。

  • フィールドは,で区切る
  • フィールドは"..."で囲んでも囲まなくてもよい
  • フィールドが,を含む場合はフィールドを"..."で囲む
  • フィールドが"を含む場合はフィールドを"..."で囲む。また""としてエスケープする

CSV出力

CSV出力するにはSET MARKUP CSVを利用します。

たとえば、employeesテーブルのデータをすべてemployees.csvに出力したいとします。この場合、まず、以下のようなemployees.sqlファイルを用意します。

employees.sql
SPOOL employees.csv

SET FEEDBACK OFF;
SET MARKUP CSV ON;

SELECT * FROM employees;

QUIT;

このemployees.sqlをsqlplusにて実行します。

sqlplus devuser/Passw0rd@oracle-db-host:1521/XEPDB1 @employees.sql

CSV入力

CSV入力するにはFIELDS CSV WITH EMBEDDEDを利用します。

たとえばemployees.csvをすべてemployeesテーブルにロードしたいとします。この場合、まず、以下のようなemployees.ctlファイルを用意します。

employees.ctl
OPTIONS (
  LOG = 'employees.log',
)
LOAD DATA
INFILE      'employees.csv'
BADFILE     'employees.bad'
DISCARDFILE 'employees.dis'
TRUNCATE INTO TABLE employees
FIELDS CSV WITH EMBEDDED (
  id,
  first_name,
  last_name
)

このemployees.ctlをSQL*Loaderにて実行します。

sqlldr userid=devuser/Passw0rd@oracle-db-host:1521/XEPDB1 control=employees.ctl

参考

環境情報

  • Oracle Database 21c Express Edition Release 21.0.0.0.0
  • SQL*Plus: Release 21.0.0.0.0 - Production
  • SQL*Loader: Release 19.0.0.0.0
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?