问题是在脚本中使用变量对我来说意味着它将在SQL * Plus中使用。
问题是您错过了引号,Oracle无法将值解析为数字。
SQL> DEFINE num = 2018
SQL> SELECT &num AS your_num FROM dual;
old 1: SELECT &num AS your_num FROM dual
new 1: SELECT 2018 AS your_num FROM dual
YOUR_NUM
----------
2018
Elapsed: 00:00:00.01
由于自动类型转换(或任何所谓的),该示例工作正常。
如果通过在SQL * Plus中键入DEFINE进行检查,它将显示num变量为CHAR。
SQL>define
DEFINE NUM = "2018" (CHAR)
在这种情况下这不是问题,因为Oracle可以将字符串解析为数字(如果它是有效数字)。
当字符串无法解析为数字时,则Oracle无法对其进行处理。
SQL> DEFINE num = 'Doh'
SQL> SELECT &num AS your_num FROM dual;
old 1: SELECT &num AS your_num FROM dual
new 1: SELECT Doh AS your_num FROM dual
SELECT Doh AS your_num FROM dual
*
ERROR at line 1:
ORA-00904: "DOH": invalid identifier
用引号引起来,所以不要强迫Oracle将其解析为数字,可以:
17:31:00 SQL> SELECT '&num' AS your_num FROM dual;
old 1: SELECT '&num' AS your_num FROM dual
new 1: SELECT 'Doh' AS your_num FROM dual
YOU
---
Doh
因此,要回答原始问题,应该像以下示例所示:
SQL> DEFINE stupidvar = 'X'
SQL>
SQL> SELECT 'print stupidvar:' || '&stupidvar'
2 FROM dual
3 WHERE dummy = '&stupidvar';
old 1: SELECT 'print stupidvar:' || '&stupidvar'
new 1: SELECT 'print stupidvar:' || 'X'
old 3: WHERE dummy = '&stupidvar'
new 3: WHERE dummy = 'X'
'PRINTSTUPIDVAR:'
-----------------
print stupidvar:X
Elapsed: 00:00:00.00
还有另一种方法可以通过使用以下方式在SQL * Plus中存储变量 Query Column Value。
在COL [UMN]具有NEW_VALUE从查询的字段名选项储存价值。
SQL> COLUMN stupid_column_name new_value stupid_var noprint
SQL> SELECT dummy || '.log' AS stupid_column_name
2 FROM dual;
Elapsed: 00:00:00.00
SQL> SPOOL &stupid_var.
SQL> SELECT '&stupid_var' FROM DUAL;
old 1: SELECT '&stupid_var' FROM DUAL
new 1: SELECT 'X.log' FROM DUAL
X.LOG
-----
X.log
Elapsed: 00:00:00.00
SQL>SPOOL OFF;
如您所见,X.log值已设置到stupid_var变量中,因此我们可以在当前目录中找到一个X.log文件,其中包含一些日志。