使用 Oracle 替换变量进行查询

Query using Oracle substitution variables

我有一个示例 SQL 代码如下

select *
  from Engg_Studens
 where Student_Name = '&Student_Name'
   And Department = 'computer science & Engineering' ;

我的问题是:运行 SQL 时,它要求部门名称中 '& engineering' 的替换变量。 我应该只被要求 '&student_name'.

您不能编写包含“&”字符的语句。

尝试如下:

select * from Engg_Studens where Student_Name = '&Student_Name' 
and Department = 'computer science '|| chr(38) ||' Engineering' ;

您可以转义第二个符号 (&),但老实说,我从来不记得如何做到这一点。我通常会这样做:

SELECT *
  FROM engg_studens
 WHERE student_Name = '&Student_Name'
   AND department = 'Computer Science &' || ' Engineering';

此处使用连接 (||) 运算符可避免替换变量。

另一种方法是 change the substitution character 您确定不会在其他地方使用的东西:

SQL> set define ^

SQ> select *
  from Engg_Studens
 where Student_Name = '^Student_Name'
   And Department = 'computer science & Engineering'

Enter value for student_name: Arif
old   3:  where Student_Name = '^Student_Name'
new   3:  where Student_Name = 'Arif'

现在只有 ^Student_Name 被视为替代变量,因此您只会得到提示。

您也可以将提示与查询分开并切换到使用实际的绑定变量,但这在这里似乎有点过分了。