简体   繁体   English

如何在SQL脚本中使用Perl变量(使用反引号)

[英]How to use a Perl variable in a SQL script (using backticks)

I have seen various examples but I am unable to use DBI. 我已经看到了各种示例,但是我无法使用DBI。 How would I use a perl variable in an external sql script? 如何在外部sql脚本中使用perl变量? For example the code in the perl script I would want would be: 例如,我想要的perl脚本中的代码是:

$text = 'Germany';
@sql_output = `sqlplus -s user/pass\@databasename <<!
 @/pathtofile/test.sql;
  QUIT;
  !`;
print @sql_output;

The sql script would be: sql脚本为:

SELECT DISTINCT City FROM Customers
Where Country = '$text'

(Just as an example, I'm using the code comes from w3schools.com sql tutorial http://www.w3schools.com/SQl/trysql.asp?filename=trysql_select_distinct ) (仅作为示例,我使用的代码来自w3schools.com sql教程http://www.w3schools.com/SQl/trysql.asp?filename=trysql_select_distinct

An example that I found through searching had: 我通过搜索发现的一个例子有:

@/pathtofile/test.sql $text;

But it did not work when I tried it with my code. 但是当我用代码尝试时,它不起作用。 Is this the correct way to incorporate a perl variable into an external sql script? 这是将perl变量合并到外部sql脚本中的正确方法吗?

  1. Define your replacement variable(s) 定义您的替换变量
  2. Use them in a here doc based on the content of your test.sql 根据您的test.sql内容在此处文档中使用它们
  3. Save it to test.sql 将其保存到test.sql
  4. Execute your backtick command 执行反引号命令

OR 要么

  • If you want to learn basic SQL: Install a DBMS with a GUI that allows interactive/ad hoc queries (eg SQLite/SQliteman/SQLite browser plugin, MySQL/MySQLWorkbench, Access, OO/LO Base, ...) 如果您想学习基本的SQL,请执行以下操作:安装具有允许交互式/临时查询的GUI的DBMS(例如SQLite / SQliteman / SQLite浏览器插件,MySQL / MySQLWorkbench,Access,OO / LO Base等)
  • If you want to work with Oracle: Concentrate on a complete/working install (which includes DBD:Oracle if your scripting language is Perl) 如果要使用Oracle,请:进行完整/有效的安装(如果脚本语言为Perl,则包括DBD:Oracle)

This one works, basically the flow is as below 这一项工作,基本上流程如下

  1. Open the SQL File 打开SQL文件
  2. Replace the $text with the variable value 将$ text替换为变量值
  3. Write it to the temporary file 将其写入临时文件
  4. Execute SQL plus on the temporary file (Every time when you re-run this it will replace the file) 在临时文件上执行SQL plus(每次重新运行时,它将替换该文件)

Try out and let me know. 试试吧,让我知道。

test.pl test.pl

#!/usr/bin/perl

$text = 'Germany1';
open(HEADER,"SQLQuery.sql");
while(<HEADER>) { $_ =~ s/\$text/$text/g; $output .= $_; }
close(HEADER);

print "$output";


open (MYFILE, '>SQLQueryTemp.sql'); 

print MYFILE $output;

close(MYFILE);

#SQLQueryTemp.sql contains the $text replaced with 'Germany'

#@sql_output = `sqlplus -s user/pass\@databasename <<!
 #@/pathtofile/SQLQueryTemp.sql;
  #QUIT;
  #!`;
#print @sql_output;

SQLQuery.sql SQLQuery.sql

SELECT DISTINCT City FROM Customers
Where Country = '$text'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM