Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make SQL Developer/SQL+ prompt only once for a substitution variable that occurs multiple times in a single statement?

I have a query roughly like this:

 select * 
  from A_TABLE 
  where A_COLUMN = '&aVariable'
    union
 select * 
  from A_TABLE 
  where B_COLUMN = '&aVariable';

But when I run it, SQL Developer prompts me for the variable twice, even though it's the same variable.

If there's a way to make it prompt only once for a variable that is used twice, how do I do it?

I do not want to use a script, it must be a single executable query.

like image 336
Trampas Kirk Avatar asked Apr 09 '09 18:04

Trampas Kirk


People also ask

How do you avoid variable substitution in Oracle SQL Developer?

You can bypass the prompts for values associated with substitution variables by passing values to parameters in a command file through the START command. You do this by placing an ampersand (&) followed by a numeral in the command file in place of a substitution variable.

Which substitution variable would you use if you want to reuse the variable by prompting the user each time before executing the SQL statement?

Use the double-ampersand (&&) if you want to reuse the variable value vvithout prompting the user each time.

Why is SQL asking for substitution variable?

This happens because when you define variables this way, the value is not stored anywhere. The variable is just substituted by the value and the value is discarded, so if the variable appears again, SQL Developer will prompt for a value again.

How do you use substitution variables in SQL?

You can use substitution variable in select statement, order by clause or where condition. Select employee_id,First_name,job_id from Employees where employee_id=&Emp_no; The above query will ask input for Employee_id in box format. User needs to give employee_id to fetch the data.


2 Answers

As I was forming this post, I figured out how to do it:

 :a_var
 select * 
  from A_TABLE 
  where A_COLUMN = :a_var
    union
 select * 
  from A_TABLE 
  where B_COLUMN = :a_var;

SQL Developer will then prompt for a bind variable, you can enter it and hit apply.

like image 176
Trampas Kirk Avatar answered Oct 06 '22 01:10

Trampas Kirk


select * 
  from A_TABLE 
  where A_COLUMN = '&aVariable'
    union
 select * 
  from A_TABLE 
  where B_COLUMN = '&&aVariable';

Notice how the 2nd (and subsequent) variables will use double-ampersand (&&)

like image 24
user313218 Avatar answered Oct 06 '22 00:10

user313218