将从文件读取的值作为输入传递给 Oracle 中的 SQL 查询

Pass values read from a file as input to an SQL query in Oracle

#cat file.txt
 12354
 13456
 13498

#!/bin/bash
for i in `cat file.txt`
do
    sqlplus XXXXX/XXXXX@DB_NAME << EOF 
        select *from TABLE_NAME where id="$i"
    EOF
done

这对我不起作用。帮我解决这个问题。

这里是使用 heredoc << 的正确方法,同时选择 while read 而不是 for 来读取文件:

#!/bin/bash

while read -r value; do
  sqlplus xxxxx/xxxxx@db_name << EOF
    select * from table_name where id='$value';
    # make sure heredoc marker "EOF" is not indented
EOF
done < file.txt

另请参阅:

  • How can I write a here doc to a file in Bash script?

  • BashFAQ001 了解为什么 for 循环不是从文件中读取文本行的最佳方式。

@codeforester 给出的解决方案有效。但是我无法使用它,因为它创建的数据库连接数与文件中的行数一样多,这是一个潜在的影响。

为了克服这个问题,我选择了下面的解决方案,它可能并不理想,但只需要一个数据库连接就可以完成这项工作。

考虑 file.txt

中的相同数据
 12354
 13456
 13498

我使用下面的 sed 命令将上面的内容填充到单个变量“12354,13456,13498”

myvariable=$(echo "`cat file.txt | sed '$!s/$/,/g' | tr -d '\n' | tr -d ' '`")

现在下面的脚本会将此变量传递给 SQL 查询并将数据假脱机到文本文件中:

#!/bin/bash
myvariable=$(echo "`cat file.txt | sed '$!s/$/,/g' | tr -d '\n' | tr -d ' '`")
echo @myvariable
sqlplus /nolog << EOF
CONNECT user@dbname/dbpassword
SPOOL dboutput.txt
select column1 from table_name where id in ($myvariable);
SPOOL OFF
EOF

输出存储在 dboutput.txt 中(与 SQL 查询一起)

cat dboutput.txt
SQL>   select column1 from table_name where id in (12354,13456,13498);

NAME
----------------------------------------------------------------------------  ----
data1
data2
data3

SQL> spool off