简体   繁体   中英

How do I set a substitution variable to the result of a query in SQL Developer?

I want to do something like this in Oracle's SQL Developer (v17.2) against an Oracle 12c database:

define thisenv = '(select name from v$database)'
select &thisenv env, count(1) from phone;

I want the select to return something like this:

ENV      COUNT(1)
------ ----------
Dev1            7

If I use my sample code, I get told, effectively, that I need a group by clause because it is seeing the query instead of a string literal that is the result of the query. But adding a group by is not going to work for me.

Per the answer to this question , I tried replacing the first line with

column dummyenv new_value thisenv
select name dummyenv from v$database;

I have also tried using a bind variable instead, but I still get prompted for a value for thisenv. So, those options don't work.

What else should I try?

The PHONE table looks like this:

PHONEID PERSONID PHONENUM     TYPE
------- -------- ------------ ----
899250  ABC12345 123-456-7890 WORK

You could count the phones in a scalar subquery:

SELECT name, 
       (SELECT count(*) FROM phone) as phones
  FROM v$database;

Alternatively, as the select privileges to the view v$database are often not granted, you can use the function sys_context . Because it is a scalar, you can just put it in the query:

SELECT sys_context('userenv', 'db_name') as db_name, count(*)
  FROM phone;

Never mind the substitution variable - you are starting with the following SQL statement, which is syntactically incorrect:

select ( select name from ... ), count(1) from ...

- this does not fail due to the use of a substitution variable, it fails as a simple SQL statement.

If you want that output (as you show it), rewrite the query as

select name, ct
from   (select name from v$database)
       cross join
       (select count(1) as ct from phone);

Now you can use a substitution variable if need be:

SQL> define thisenv = '(select name from v$database)'
SQL> select name, ct
  2  from   &thisenv
  3  cross join
  4  (select count(1) as ct from phone);

Of course, when I run this on my machine I get an error (since I don't have a table PHONE ), but it should work for you. It does work for me when I use an existing table name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM