Oracle SQL 开发人员中的脚本变量

Script Variables in Oracle SQL Developer

给定两个表

USERS
UID NAME
1   KEN

ADRESS
AID UID CITY
1    1  LONDON

我想要一个 Oracle SQL 开发人员脚本,它可以输出两个结果表,就像我一个接一个地输入两个 select 语句一样。

这不起作用,我无法分配 u_id 变量:

select UID into u_id from USERS where NAME='KEN';
select * from USERS where UID = u_id;
select * from ADRESS where UID = u_id;

输出当然应该是

UID NAME
1   KEN

AID UID CITY
1    1  LONDON

在 SQL Developer 中至少有两种方法可以做到这一点。

绑定变量:

variable u_id number

execute select U_ID into :u_id from USERS where U_NAME='KEN';

select * from USERS where U_ID = :u_id;
select * from ADRESS where U_ID = :u_id;

或使用替换变量:

column U_ID new_value sub_u_id;
set verify off

select U_ID from USERS where U_NAME='KEN';

select * from USERS where U_ID = &sub_u_id;
select * from ADRESS where U_ID = &sub_u_id;

在这种情况下,您可以简化为:

column U_ID new_value sub_u_id;
set verify off

select * from USERS where U_NAME='KEN';
select * from ADRESS where U_ID = &sub_u_id;

在 SQL*Plus 文档中阅读有关 variable command, the execute command, the column command and it's new_value clause, and substitution variables 的更多信息 - 其中大部分内容也适用于 SQL 开发人员。

使用略有不同的列名创建表的演示,以避免 key/reserved 个单词:

create table USERS (U_ID number, U_NAME varchar2(10));
insert into users values (1, 'KEN');
create table ADRESS(A_ID number, U_ID number, CITY varchar2(10));
insert into adress values (1, 1, 'LONDON');

prompt Demo 1: bind variables

var u_id number
exec select U_ID into :u_id from USERS where U_NAME='KEN';
select * from USERS where U_ID = :u_id;
select * from ADRESS where U_ID = :u_id;

prompt Demo 2: substitution variables

column U_ID new_value sub_u_id;
set verify off
select * from USERS where U_NAME='KEN';
select * from ADRESS where U_ID = &sub_u_id;

运行作为脚本,脚本输出window显示:

Table USERS created.

1 row inserted.

Table ADRESS created.

1 row inserted.

Demo 1: bind variables

PL/SQL procedure successfully completed.

      U_ID U_NAME   
---------- ----------
         1 KEN       


      A_ID       U_ID CITY     
---------- ---------- ----------
         1          1 LONDON    

Demo 2: substitution variables

      U_ID U_NAME   
---------- ----------
         1 KEN       

      A_ID       U_ID CITY     
---------- ---------- ----------
         1          1 LONDON    

当然,您可以使用 set feedback off 来抑制 PL/SQL procedure successfully completed 消息。