bash 将变量从bash shell传递到sql文件到oracle表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14131955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:08:18  来源:igfitidea点击:

passing variable from bash shell to sql file to oracle table

bashoracle11gsqlplus

提问by user1813261

I have set variables in my .shfile (ex. ENV=$1 RELEASE_ID=$2) within my.shfile. I sqlplusinto my sql file like

我在my .sh文件中的文件(例如ENV=$1 RELEASE_ID=$2)中设置了变量my.sh。我sqlplus进入我的 sql 文件

sqlplus -S $username/password@destination @/path/copysetup/insert.sql

I want to pass variables ENV=$1RELEASE_ID=$2calling from a unix prompt into my sql file as

我想ENV=$1RELEASE_ID=$2将从 unix 提示符调用的变量传递到我的 sql 文件中

copysetup.sh env01 release 1.0

from my sql file I want to pass the same variable into an oracle table

从我的 sql 文件中,我想将相同的变量传递到 oracle 表中

insert into table...

Can someone assist on how to pass variable from bash shell script to sql file and ultimately insert the into my oracle table?

有人可以协助如何将变量从 bash shell 脚本传递到 sql 文件并最终插入到我的 oracle 表中吗?

回答by DazzaL

Pass the parameters on the command line:

在命令行传递参数:

sqlplus -S $username/password@destination @/path/copysetup/insert.sql $ENV $RELEASE_ID

then in the SQL script they become &1 and &2 (ensure you have set scan onat the top of the SQL script)

然后在 SQL 脚本中它们变成 &1 和 &2(确保您set scan on在 SQL 脚本的顶部)

eg

例如

set scan on
insert into foo (env, release) values ('&1', '&2');
commit;

回答by ryanbwork

Assuming your insert.sql file is the one which you'd like to insert an environment variable (or any bash variable), you can use sedto find/replace a some placeholder text with your desired value. For instance, if your insert.sql file looked something like

假设您的 insert.sql 文件是您想要插入环境变量(或任何 bash 变量)的文件,您可以使用sed查找/替换一些具有所需值的占位符文本。例如,如果您的 insert.sql 文件看起来像

INSERT INTO @mytable VALUES (1,'sometext');

You could use sed to find/replace the @mytablestring with the data stored in $MYVARusing the following syntax in a bash script

您可以使用 sed在 bash 脚本@mytable$MYVAR使用以下语法使用存储的数据查找/替换字符串

sed "s/@mytable/$MYVAR" insert.sql > modifiedinsert.sql

Now this would generate a new file, modifiedinsert.sql which you'd then pass into sqlplus.

现在这将生成一个新文件 modifiedinsert.sql,然后您将其传递给 sqlplus。