2

我正在使用 shell 脚本调用 Oracle sqlplus,并且我想将查询结果导出到 sql 文件。

这个请求给了我很多价值:

SELECT * FROM CUST_TABLE WHERE  CUST_CITY = 'San Fran';

我希望我的脚本生成一个这样的 sql 文件:

evariste@Unix-Server$cat first_query_result.sql

INSERT INTO CUST_TABLE (COLUMN_1, COLUMN_2, ....)
VALUES (CUST1_COLUMN_1, CUST1_COLUMN_2, ...);
INSERT INTO CUST_TABLE (COLUMN_1, COLUMN_2, ....)
VALUES (CUST2_COLUMN_1, CUST2_COLUMN_2, ...);
INSERT INTO CUST_TABLE (COLUMN_1, COLUMN_2, ....)
VALUES (CUST3_COLUMN_1, CUST3_COLUMN_2, ...);

关于如何在我的脚本中执行它的任何想法(我对 Oracle 和 SQL 有一点背景)?

4

1 回答 1

3

沿着这些思路,也许:

sqlplus -silent uid/pw@db <<+EOF
set heading off
set feedback off
set pagesize 0
set linesize 32000
set trimspool on
set termout off
set echo off
set verify off
set sqlblanklines off
spool somefile.sql
WITH cust_table AS 
(SELECT 1 id, 'San Francisco' city, 'C1V1' col1, 'C2V1' col2 FROM dual
 UNION ALL SELECT 2, 'Los Angeles', 'C1V2', 'C2V2' FROM dual
 UNION ALL SELECT 3, 'San Jose', 'C1V3', 'C2V3' FROM dual
 UNION ALL SELECT 4, 'San Francisco', 'C1V4', 'C2V4' FROM dual)
SELECT 'INSERT INTO cust_table (id, city, col1, col2)'||CHR(10)||'VALUES ('||
       id||','''||city||''','''||col1||''','''||col2||''');'
  FROM cust_table
 WHERE city = 'San Francisco';
quit;
+EOF

这会产生一个文件 somefile.sql ,其内容如下:

INSERT INTO cust_table (id, city, col1, col2)
VALUES (1,'San Francisco','C1V1','C2V1');
INSERT INTO cust_table (id, city, col1, col2)
VALUES (4,'San Francisco','C1V4','C2V4');
于 2012-06-16T16:42:39.510 回答