如何将表达式的结果分配给 SQL 替换变量?
How do you assign the result of an expression to an SQL substitution variable?
你能计算一个表达式并将结果赋给一个替换变量吗?
在我的例子中,我需要调用一个包含替换变量的旧脚本。在调用脚本之前,我需要计算该变量的值。我正在使用 Oracle SQL 和 SQL*Plus
这是基本问题:
def this_num = 2+2
@old_script
里面old_script.sql
select '&this_num' from dual; -- Probably shouldn't change this
产量:
'2+2'
有没有办法强制求值,以便替代变量获得表达式的 结果 而不是表达式本身?
def this_num = 2+2
@old_script
在old_script
中,你可以说
select &this_num from dual;
您不需要在变量名周围使用 ''
。这应该有效。
可行的解决方案
我在这里找到了有效的答案:https://blogs.oracle.com/opal/entry/sqlplus_101_substitution_varia#2_5
这是相关的文字。
2.5 Storing a Query Column Value in a Substitution Variable
Data stored in the database can be put into substitution variables:
SQL> column last_name new_value mynv
SQL> select last_name from employees where employee_id = 100;
The NEW_VALUE option in the COLUMN command implicitly creates a
substitution variable called "mynv". The variable is not physically
created until a query references the column LAST_NAME. When the query
finishes, the variable "mynv" holds the last retrieved value from
column "last_name":
SQL> define mynv
DEFINE mynv = "King" (CHAR)
所以你这样做:
column DUMMY_COLUMN_NAME new_value THIS_NUM
select 2+2 DUMMY_COLUMN_NAME from dual;
select '&&THIS_NUM' from dual;
'4'
------------
4
多田!
邪恶的解决方案
为了娱乐价值,这里有一个非常邪恶的解决方法,如果变量碰巧在引号之外使用,它就会中断:
define this_num = "' || 2+2 ||'" (CHAR)
然后:
select '&&this_num' from dual;
计算结果为:
select '' || 2+2 ||'' from dual;
产生:
'
4
你能计算一个表达式并将结果赋给一个替换变量吗?
在我的例子中,我需要调用一个包含替换变量的旧脚本。在调用脚本之前,我需要计算该变量的值。我正在使用 Oracle SQL 和 SQL*Plus
这是基本问题:
def this_num = 2+2
@old_script
里面old_script.sql
select '&this_num' from dual; -- Probably shouldn't change this
产量: '2+2'
有没有办法强制求值,以便替代变量获得表达式的 结果 而不是表达式本身?
def this_num = 2+2
@old_script
在old_script
中,你可以说
select &this_num from dual;
您不需要在变量名周围使用 ''
。这应该有效。
可行的解决方案
我在这里找到了有效的答案:https://blogs.oracle.com/opal/entry/sqlplus_101_substitution_varia#2_5
这是相关的文字。
2.5 Storing a Query Column Value in a Substitution Variable
Data stored in the database can be put into substitution variables:
SQL> column last_name new_value mynv SQL> select last_name from employees where employee_id = 100;
The NEW_VALUE option in the COLUMN command implicitly creates a substitution variable called "mynv". The variable is not physically created until a query references the column LAST_NAME. When the query finishes, the variable "mynv" holds the last retrieved value from column "last_name":
SQL> define mynv DEFINE mynv = "King" (CHAR)
所以你这样做:
column DUMMY_COLUMN_NAME new_value THIS_NUM
select 2+2 DUMMY_COLUMN_NAME from dual;
select '&&THIS_NUM' from dual;
'4'
------------
4
多田!
邪恶的解决方案
为了娱乐价值,这里有一个非常邪恶的解决方法,如果变量碰巧在引号之外使用,它就会中断:
define this_num = "' || 2+2 ||'" (CHAR)
然后:
select '&&this_num' from dual;
计算结果为:
select '' || 2+2 ||'' from dual;
产生:
'
4