NathanSmutz
NathanSmutz

Reputation: 31

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

Can you evaluate an expression and assign the result to a substitution variable?

In my case, I need to call an old script which contains a substitutions variable. I need to calculate a value for that variable before calling the script. I'm using Oracle SQL and SQL*Plus

Here's the basic problem:

def this_num = 2+2
@old_script

Inside old_script.sql

select '&this_num' from dual;  -- Probably shouldn't change this

Yields: '2+2'

Is there a way to force evaluation so that the substitution variable gets the result of an expression rather than the expression itself?

Upvotes: 1

Views: 468

Answers (2)

NathanSmutz
NathanSmutz

Reputation: 31

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

Upvotes: 0

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49270

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.

Upvotes: 1

Related Questions