简体   繁体   English

如何在SQL Developer中将替换变量设置为查询结果?

[英]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: 我想在Oracle SQL Developer(v17.2)中针对Oracle 12c数据库执行以下操作:

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. 如果使用示例代码,则会有效地告知我需要一个group by子句,因为它正在查看查询,而不是查询结果的字符串文字。 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. 我也尝试使用绑定变量来代替,但是仍然会提示我输入thisenv的值。 So, those options don't work. 因此,这些选项不起作用。

What else should I try? 我还应该尝试什么?

The PHONE table looks like this: PHONE表如下所示:

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 . 另外,由于通常不授予对视图v$database的选择特权,因此可以使用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: 不用担心替换变量-您从以下SQL语句开始,该语句在语法上是不正确的:

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. -这不会因使用替换变量而失败,它会作为简单的SQL语句失败。

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. 当然,当我在计算机上运行此命令时,会出现错误(因为我没有表PHONE ),但是它应该对您PHONE It does work for me when I use an existing table name. 当我使用现有表名时,它确实对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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