How do you assign the result of an expression to an SQL substitution variable?

倾然丶 夕夏残阳落幕 提交于 2019-12-07 05:31:35
def this_num = 2+2
@old_script

In the old_script, you can say

select &this_num from dual;

You don't need to use '' around the variable name. This should work.

The Working Solution

I found a working answer here: https://blogs.oracle.com/opal/entry/sqlplus_101_substitution_varia#2_5

Here's the relevant text.

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)

So you do it like this:

column DUMMY_COLUMN_NAME new_value THIS_NUM
select 2+2 DUMMY_COLUMN_NAME from dual;

select '&&THIS_NUM' from dual;

'4'
------------
           4

Tada!

The Evil Solution

For entertainment value, here's a really evil workaround which would break if the variable ever happens to be used outside of quotes:

define this_num = "' || 2+2 ||'" (CHAR)

Then:

select '&&this_num' from dual;

evaluates to:

select '' || 2+2 ||'' from dual;

Which yields:

'

4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!