SPOOL

-----How to Pass UNIX Variable to SPOOL Command (Doc ID 1029440.6)
setenv只有csh才有不行啊PROBLEM DESCRIPTION:
====================You would like to put a file name in Unix and have SQL*Plus read that file name, 
instead of hardcoding it, because it will change.You want to pass a Unix variable on the command line like:SQL*Plus -s <user>/<password>@test.sql $SPOOLand have the $SPOOL value be passed into existing SQL.SOLUTION DESCRIPTION:
=====================This syntax will not work because everything after the word 'SQL*Plus' is taken 
as arguments passed in to SQL*Plus, and SQL*Plus does not expand 
(or even recognize) the shell variable.  One way around this is to set the SPOOL variable just prior to running the 
script.  For example:set the SPOOL variable with this line:setenv SPOOL /u02/usrname/spoolfile.Then you create a file called testfile.sql that contained the lines:spool $SPOOL;select user from dual;select count(*) from dba_tables;And you then type 'SQL*Plus -s <user>/<password> @testfile.sql'.
The $SPOOL variable will be expanded inside the file to generate the file 
/u02/usrname/spoolfile.lst for the session.  Once exported, shell variables can 
be referenced one level down from their defining shell.

-------generate a grant script:

spool generate_sql.sql
set long 9999999
set header off

SQL> select 'GRANT READ, SELECT on ' || owner || '.' || table_name || ' to <user_name>;' from dba_tables;   -- Replace <user_name> with the user you want to give permissions to.

spool off

---------------set 这些如果直接执行不行------------

SQL> set NEWPAGE 0
SQL> set SPACE 0
SQL> set LINESIZE 80
SQL> set PAGESIZE 0
SQL> set ECHO OFF
SQL> set FEEDBACK OFF
SQL> set HEADING OFF
SQL> spool report.txt
SQL> select sysdate from dual; 
10-JUN-24
SQL> spool off
SQL> exit
Disconnected from Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.20.0.0.0
[oracle@rac1 ~]$ cat report.txt
SQL> select sysdate from dual;
10-JUN-24                                                                       
SQL> spool off

 

goal: How To Create a flat file Without Showing Statement Or ''Spool Off''
fact: SQL*Plus

fix:

Create a script, e.g. report.sql, with the following contents:
set NEWPAGE 0
set SPACE 0
set LINESIZE 80
set PAGESIZE 0
set ECHO OFF
set FEEDBACK OFF
set HEADING OFF
spool report.txt
select sysdate from dual;     <--- your SQL statement here
spool off

Run the script from SQL*Plus:
SQL> @report.sql

-----spool 两个..

Case 1
------
In SQL*Plus, how do you spool data to a file with a
.TXT file extension?When you issue the following line of code:SPOOL myfilethis automatically spools data to MYFILE.LST.
How do you spool to MYFILE.TXT?Case 2
------
You are spooling to a filename that the user passes in as
a substitution variable.  How do you append a .TXT file
extension, as opposed to the default .LST, to the 
filename?Sample script:SPOOL &&filenameSELECT * FROM dept/SPOOL OFFIf you enter MYFILE for filename, MYFILE.LST is the default
spooled filename.  How do you spool to MYFILE.TXT?Solution Description:
=====================Case 1
------
Specify the .TXT extension after the filename:SPOOL myfile.txtCase 2
------
If you are spooling to a substitution variable,
specify "..txt" after the substitution variable.SPOOL &&filename..txtSELECT * FROM dept/SPOOL OFFIf you enter MYFILE for filename, this stores data into the
MYFILE.TXT file.Make sure to append 2 periods ("..") to the substitution variable.
If you only include 1 period and enter MYFILE for filename,
this stores data into the MYFILETXT.LST file.

-----------------------加上Oracle SID

How is "@" interpretted when used in spooled file name?
========================================================
When you spool output to file with "@" included in the file name, the "@" is 
replaced with ORACLE_SID value.  

-rw-r--r--. 1 oracle oinstall      500 Jun 10 13:30 TESTcdb1..txt
[oracle@rac1 ~]$ cat testfile1.sql
   spool  &&filename@..txt            ---------------这里不能两个.
   select user from dual;
   select count(*) from dba_tables;
[oracle@rac1 ~]$ cat TESTcdb1..txt

USER                                                                            
--------------------------------------------------------------------------------
SYS                                                                             


  COUNT(*)                                                                      
----------                                                                      
      2202                                                                      

SQL> exit

-rw-r--r--. 1 oracle oinstall       88 Jun 10 13:31 testfile1.sql
-rw-r--r--. 1 oracle oinstall      496 Jun 10 13:31 T11cdb1.txt
[oracle@rac1 ~]$ cat T11cdb1.txt

USER                                                                            
--------------------------------------------------------------------------------
SYS                                                                             


  COUNT(*)                                                                      
----------                                                                      
      2202                                                                      

SQL> -----这里为什么没有exit 因为我用ctrl D退出的
[oracle@rac1 ~]$ cat  testfile1.sql
   spool  &&filename@.txt
   select user from dual;
   select count(*) from dba_tables;
 

----How can you generate a spool file format c:\temp\Overnight_13FEB06.log?

SOLUTION

Sample script:

COLUMN SPOOL_DATE NEW_VALUE FILE_DATE
COLUMN SPOOL_PREFIX NEW_VALUE FILE_PREFIX
COLUMN SPOOL_SUFFIX NEW_VALUE FILE_SUFFIX
SELECT
TO_CHAR(SYSDATE,'YYYYMMDD') SPOOL_DATE,
'c:\temp\Overnight_' SPOOL_PREFIX,
'.log' SPOOL_SUFFIX
FROM
DUAL
/
SPOOL &FILE_PREFIX.&FILE_DATE.&FILE_SUFFIX
/
report
/
SPOOL OFF

[oracle@rac1 ~]$ cat  spooldate.sql
COLUMN SPOOL_DATE NEW_VALUE FILE_DATE
COLUMN SPOOL_PREFIX NEW_VALUE FILE_PREFIX
COLUMN SPOOL_SUFFIX NEW_VALUE FILE_SUFFIX
SELECT
TO_CHAR(SYSDATE,'YYYYMMDD') SPOOL_DATE,
'/tmp/Overnight_' SPOOL_PREFIX,
'.log' SPOOL_SUFFIX
FROM
DUAL
/
SPOOL &FILE_PREFIX.&FILE_DATE.&FILE_SUFFIX
/
report
/
SPOOL OFF
[oracle@rac1 ~]$ 

------How to change spool file name dynamically ?


Each time query executes, the same file should not be overwritten.
It would be helpful in situations where an output of a table is 
monitored at periodic intervals to find the difference.Solution Description
--------------------
COLUMN command with NEW_VALUE can be used to accomplish this.
Have the following three lines before the query -column col1 new_value filename; 
select to_char(sysdate,'DDMONYYHH24MI') col1 from dual; 
spool &&filename..txt select .... ; -- original query 
spool off; Spool file name will contain the date and time so that they are not
overwritten.(NOTE: In the example above, user details / company name / address / email / telephone number represent a fictitious sample (based upon made up data used in the Oracle Demos).  Any similarity to actual persons, living or dead, is purely coincidental and not intended in any manner.)

------------------  script to automatically label each spool filename with a timestamp of the date and time of the script execution.

 

 

Background 

If you must execute a single SQL*Plus script several times (for example because you run a report every week or when running a script in batch mode regularly), and the scriptspools the output to a file, you may want to give a unique name to the spool file for each execution.

Script

The following SQL*Plus script illustrates the timestamp method:
 

column timecol new_value timestamp
select to_char(sysdate,'.MMDDYY_HHMISS') timecol
from sys.dual
/
spool output_&&timestamp
select sysdate from sys.dual
/
spool off

If this script is executed at 12:34:12 AM on October 17, 1999, the output would be spooled to an output file with the name 'output.101799_123412'. You can modify the date format mask ('.MMDDYY_HHMISS') and/or the constant filename portion ('output_') of the example to create different spool filename formats.

Depending on the operating system the spool file will have the suffix .LIS or .LST appended to it's name by default. To replace the default ending with your own, for example '.txt', change the script like suggested below.
 

column timecol new_value timestamp
column spool_extension new_value suffix
select to_char(sysdate,'_MMDDYY_HHMISS') timecol,
'.txt' spool_extension
from sys.dual
/
spool output_&&timestamp&&suffix
select sysdate from sys.dual
/
spool off

You can take this even a step further and give the user of your script control over the file extension of the spool file. For example on UNIX make files can process files of a designated extension. On Microsoft Windows on the other hand most file extensions are associated with certain defined actions when you for example 'Open' or 'Edit' a file.

Replace the literal '.txt' with a variable to let the user of your script decide on an file extension that is useful for them.
 

select to_char(sysdate,'_MMDDYY_HHMISS') timecol,
'.'||&file_ending spool_extension

Please note, this last option is not useful for batch files.

------------------

How to generate sql/select statement from a select statement?
Solution Description
--------------------
This sample will show how to generate a select statement from
a select statement. For example, how to dynamically create a
sql script which contains a set of select statements based on 
column values from the EMP table. Specifically, how to create
a set of select statements based on each deptno value in EMP 
and job='CLERK'?How to create this script?
==========================
[Sample script based on demo table EMP]1. The following is an example of how you can dynamically create selectstatements based on column values in table. For example, how to generateselect statements based on each deptno value and job='CLERK' in EMP table.   Use the following code to create a SQL script (This includes comments 
for better documentation):*****************************************-- Given demo table EMP.
-- The following select statement will generate a sql file withselect statements based on each department number (deptno) andjob = 'CLERK'set heading off
set feedback off
set echo off
spool temp.sqlselect distinct 'select empno, ename, job from emp where deptno='||
deptno
||' and job = '||''''||
JOB
||''''||';' query_statement
from emp
where job = 'CLERK'
/
spool off*****************************************Result
------
Executing the above script will generate temp.sql file.The temp.sql file contains: 
select empno, ename, job from emp where deptno=10 and job = 'CLERK';
select empno, ename, job from emp where deptno=20 and job = 'CLERK';
select empno, ename, job from emp where deptno=30 and job = 'CLERK';You can now execute temp.sql to run the dynamically generated select statements.

------------------spool  excel format

Use SQL*Plus SPOOL command to generate an .xlsx output file.  When attempting to open this output file in MS Excel, it fails with the following error message:

Excel cannot open the file 'spooled_output.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
  [OK]



STEPS:           

The issue can be reproduced at will when executing the following sample script in SQL*Plus:

set sqlblanklines off
set feedback off
set verify off
set heading off
set linesize 800
set pagesize 400
set echo off
set TERMOUT off
set colsep ,
set newpage none
spool /tmp/spooled_output.xlsx
select * from emp;
spool off

Then, attempt to open /tmp/spooled_output.xlsx in MS Excel.
It will fail with the reported error above.

CHANGES

Generating .xlsx output files.

CAUSE

This is a MS Excel issue, not SQL*Plus.  The SQL*Plus spool file is just a plain text file. The file extension is irrelevant. 
 

SOLUTION

Do not use .xlsx as a file extension when using SPOOL command in SQL*Plus. 

As a Workaround:
      Use .xls or .csv file extension.

Also, starting in SQL*Plus 12.2.0.1.0, there is a new "SET MARKUP CSV" which produces output in csv format.

For Example:

SQL> set markup csv on
SQL> select * from emp;

"EMPNO","ENAME","JOB","MGR","HIREDATE","SAL","COMM","DEPTNO"
7369,"<NAME1>","CLERK",7902,"17-DEC-80",800,,20
7499,"<NAME2>","SALESMAN",7698,"20-FEB-81",1600,300,30
7521,"<NAME3>","SALESMAN",7698,"22-FEB-81",1250,500,30
7566,"<NAME4>","MANAGER",7839,"02-APR-81",2975,,20
7654,"<NAME5>","SALESMAN",7698,"28-SEP-81",1250,1400,30
7698,"<NAME6>","MANAGER",7839,"01-MAY-81",2850,,30
7782,"<NAME7>","MANAGER",7839,"09-JUN-81",2450,,10
7788,"<NAME8>","ANALYST",7566,"19-APR-87",3000,,20
7839,"<NAME9>","PRESIDENT",,"17-NOV-81",5000,,10
7844,"<NAME10>","SALESMAN",7698,"08-SEP-81",1500,0,30
7876,"<NAME11>","CLERK",7788,"23-MAY-87",1100,,20
7900,"<NAME12>","CLERK",7698,"03-DEC-81",950,,30
7902,"<NAME13>","ANALYST",7566,"03-DEC-81",3000,,20
7934,"<NAME14>","CLERK",7782,"23-JAN-82",1300,,10

---------------2 spool output (Excel .csv files)

How to generate a delimiter in spool output (Excel .csv files)?

SOLUTION

1) In order to generate a delimited file output, you need to concatenate columns using the desired delimiter i.e. comma:

Example:
 

select empno|| ','||ename||'&'||mgr from X;


2) Other option is using:
 

SQL> set colsep ','
SQL> spool <DIRECTORY>/testexcel.csv
SQL> select * from emp;


3) Change some of the default SQL*Plus parameters, that will be garbage for Excel:
 

feedback=off
newpage=none
termout=off
heading=off


4) If some columns are empty, be aware to include the delimiter, too:
 

nvl(to_char(col2),',')


NOTE: If the data contain comma's as well and needs to be preserved then, the csv data needs to be encapsulated within double quotes. Example:
 

select '"' || name || '"' || ',' || '"' || department || '"' from mytable;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/26670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

快速排序 -非递归版-双指针版

个人主页点这里~ 非递归法: 快速排序的非递归实现涉及到使用一个栈来模拟递归调用栈。 因为递归调用内存的栈区一般只有8M,如果数据很多则容易栈溢出(不过现在硬件基本不会),而使用数据结构的栈来模拟实现递归是调用堆区,一般右2G. //得到key int QuickSort1(int* a, int lef…

Sui Bridge在测试网上线并推出10万SUI激励计划

是一种为Sui设计的原生桥接协议&#xff0c;专门用于在Sui与其他网络之间桥接资产和数据。今天&#xff0c;Sui Bridge宣布在测试网上线。作为一种原生协议&#xff0c;Sui Bridge能够在Ethereum和Sui之间轻松且安全地转移ETH、wBTC、USDC和USDT&#xff0c;使其成为Sui基础设施…

如果R是唯一析因整环,那么R[x]也是唯一析因整环

【定义1】商域 如果 R R R是整环&#xff0c;那么则 R R R上的商域 K R K_{R} KR​定义为 K R { a b ∣ a , b ∈ R , b ≠ 0 } K_{R} \left\{ \frac{a}{b}|a,b \in R,b \neq 0 \right\} KR​{ba​∣a,b∈R,b0} 其中 a b a ′ b ′ ∈ K R ⇔ a b ′ a ′ b ∈ R \frac…

MYSQL 三、mysql基础知识 4(存储过程与函数)

MySQL从5.0版本开始支持存储过程和函数。存储过程和函数能够将复杂的SQL逻辑封装在一起&#xff0c;应用程序无须关注存储过程和函数内部复杂的SQL逻辑&#xff0c;而只需要简单地调用存储过程和函数即可。 一、存储过程概述&#xff1a; 1.1理解&#xff1a; 含义&am…

vue项目导入 .xlsx 文件

直接上代码&#xff0c;简单示例&#xff1a; 点击导入按钮&#xff0c;弹出导入弹窗&#xff1b; template 部分的代码&#xff1a; <div><el-buttonclass"filter-item"style"margin-left: 10px; margin-bottom: 20px; height: 30px"type"…

ARM-V9 RME(Realm Management Extension)系统架构之功耗管理

安全之安全(security)博客目录导读 目录 一、系统功耗管理 1、功耗状态 2、PE功耗管理 3、系统和PE集群功耗管理 4、系统功耗状态 二、RME组件功耗管理 本节规定了RME系统的功耗管理规则。 功耗管理流程定义了系统及其组件如何在各种电源状态之间进行转换&#xff0c;以…

深度学习中的神经网络——揭秘人工智能的核心技术

在当今科技领域&#xff0c;人工智能&#xff08;Artificial Intelligence&#xff0c;简称AI&#xff09;无疑是最热门的话题之一。而作为人工智能领域的核心技术&#xff0c;神经网络&#xff08;Neural Networks&#xff09;正逐渐改变着我们的生活&#xff0c;并在诸如图像…

论文研读|以真实图像为参考依据的AIGC检测

前言&#xff1a;这篇文章介绍几篇AIGC检测的相关工作&#xff0c;其中前几篇文章是以真实图像的特征作为标准进行检测&#xff0c;最后一篇文章就当拓展一下知识边界吧&#xff5e; 目录 Detecting Generated Images by Real Images Only (202311 arXiv)Let Real Images be as…

深入解析Web通信 HTTP、HTTPS 和 WebSocket

在现代Web开发中,了解和掌握HTTP、HTTPS以及WebSocket协议是非常重要的。这些协议是实现Web应用程序之间通信的基石。本文将详细介绍这三种协议,包括它们的基本概念、工作原理、优缺点以及适用场景。通过深入解析它们的特点和应用,帮助读者更好地理解和使用这些协议。 一、…

【Chrome插件】如何在Chrome插件开发中处理复杂数据结构的存储

最近俺在接触 Chrome 插件开发&#xff0c;需要把一个数据存放到浏览器的存储中。这个数据结构有点复杂&#xff0c;它包含一个 Map 和一个数组。我使用 chrome.storage.local API来存储这个数据&#xff0c;然后在另一个地方获取数据。保存数据的代码并没有报错&#xff0c;但…

代码随想录算法训练营第37天|● 56.合并区间● 738.单调递增的数字

合并区间 56. 合并区间 - 力扣&#xff08;LeetCode&#xff09; 按照左边界从小到大排序之后&#xff0c;如果 intervals[i][0] < intervals[i - 1][1] 即intervals[i]的左边界 < intervals[i - 1]的右边界&#xff0c;则一定有重叠。&#xff08;本题相邻区间也算重贴…

SpringBoot整合H2数据库并将其打包成jar包、转换成exe文件

SpringBoot整合H2数据库并将其打包成jar包、转换成exe文件 H2 是一个用 Java 开发的嵌入式数据库&#xff0c;它的主要特性使其成为嵌入式应用程序的理想选择。H2 仅是一个类库&#xff0c;可以直接嵌入到应用项目中&#xff0c;而无需独立安装客户端和服务器端。 常用开源数…

网页自动化工具入门篇之常用自动化工具

1. Selenium 优点: 功能强大&#xff0c;可以与几乎所有的现代浏览器配合使用。支持多种编程语言&#xff08;如Python, Java, C#, Ruby等&#xff09;。能够处理复杂的网页交互&#xff0c;包括按钮点击、表单填写、拖拽操作等。 缺点: 相对较慢&#xff0c;因为它是真正启动…

Linux Debian12使用podman安装pikachu靶场环境

一、pikachu简介 Pikachu是一个带有漏洞的Web应用系统&#xff0c;在这里包含了常见的web安全漏洞。 二、安装podman环境 Linux Debian系统如果没有安装podman容器环境&#xff0c;可以参考这篇文章先安装podman环境&#xff0c; Linux Debian11使用国内源安装Podman环境 三…

【Numpy】一文向您详细介绍 np.trunc()

【Numpy】一文向您详细介绍 np.trunc() 下滑即可查看博客内容 &#x1f308; 欢迎莅临我的个人主页 &#x1f448;这里是我静心耕耘深度学习领域、真诚分享知识与智慧的小天地&#xff01;&#x1f387; &#x1f393; 博主简介&#xff1a;985高校的普通本硕&#xff0c;…

[数据集][目标检测]中国象棋检测数据集VOC+YOLO格式300张12类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;300 标注数量(xml文件个数)&#xff1a;300 标注数量(txt文件个数)&#xff1a;300 标注类别…

Django后台忘记管理员的账号

使用命令启动项目&#xff1a; python manage.py runserver输入后缀/admin&#xff0c;进入后台管理员&#xff0c;如果此时忘记你先前设置的用户名与密码怎么办&#xff1f; 终端输入&#xff1a; python manage.py shell 输入以下内容&#xff0c;并查看返回结果&#xff…

用【R语言】揭示大学生恋爱心理:【机器学习】与【深度学习】的案例深度解析

目录 第一部分&#xff1a;数据收集与预处理 1.1 数据来源 1.2 数据清洗 1.3 数据探索性分析 第二部分&#xff1a;特征工程与数据准备 2.1 特征选择 2.2 特征提取 第三部分&#xff1a;机器学习模型 3.1 逻辑回归模型 3.2 决策树模型 第四部分&#xff1a;深度学习…

spark MLlib (DataFrame-based) 中的聚类算法Bisecting K-Means、K-Means、Gaussian Mixture

Bisecting K-Means 核心原理&#xff1a; Bisecting K-Means 是一种层次 K-Means 聚类算法&#xff0c;基于 Steinbach、Karypis 和 Kumar 的论文《A comparison of document clustering techniques》&#xff0c;并对 Spark 环境进行了修改和适应。 该算法通过递归地将数据集…