首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从shell脚本调用.sql脚本时出错

从shell脚本调用.sql脚本时出错
EN

Stack Overflow用户
提问于 2017-11-16 08:50:15
回答 1查看 1.2K关注 0票数 0

各位,

我试图从shell脚本中调用带有1个参数的sql脚本。我的脚本如下

tab.sql

代码语言:javascript
复制
set lines 500
col file_name for a80

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/

我的shell脚本是test.sh

代码语言:javascript
复制
#!/bin/bash

LOC=`pwd`

echo -n "Enter the name of the Tablespace: "
read -r TAB_NAME

sqlplus "/ as sysdba" <<- EOF
@$LOC/tab.sql $TAB_NAME
EOF

exit

当我执行脚本时,这就是我要得到的

代码语言:javascript
复制
sh test.sh
Enter the name of the Tablespace: users

SQL*Plus: Release 11.2.0.4.0 Production on Thu Nov 16 14:17:45 2017

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Connected.
SQL> Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
SQL> Disconnected

有人能告诉我这里出了什么问题吗?我在网上搜索了这个SP2-0546,但没有解决我的问题。我在OLE-6上使用11.2.0.4db

谢谢

EN

回答 1

Stack Overflow用户

发布于 2017-11-16 09:35:33

您混淆了命名位置性替换变量,可能还会将它们与shell变量混淆一些。您可以在位置上引用在SQL*Plus命令行上传递的参数:

代码语言:javascript
复制
select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&1');
/

如果您愿意,您可以定义一个命名的替换变量;在这里可能会过度使用,但对于更大的脚本中的清晰性是有用的:

代码语言:javascript
复制
define TAB_NAME=&1

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/

或者简化以后的引用:

代码语言:javascript
复制
define TAB_NAME=upper('&1')

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=&TAB_NAME;
/

注意,在这个版本中,对&TAB_NAME的引用不包含在单引号中,因为它们是在替换过程中应用的。

我可以在测试/调试时帮助set verify on,然后用set verify off来真正的隐藏噪音。您可能还会发现,在-s调用中包含sqlplus标志以隐藏横幅文本也是有用的。在本例中,您甚至不需要一个heredoc,您也可以直接从命令行运行脚本:

代码语言:javascript
复制
sqlplus -s "/ as sysdba" @$LOC/tab.sql $TAB_NAME

(作为常规查询的sys连接并不理想;最好让一个拥有特权的普通用户查看您需要查询的数据字典表,但这是另一个主题.)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47325231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档