2016-06-21 53 views
0

给定两个表脚本变量在Oracle SQL Developer中

USERS 
UID NAME 
1 KEN 

ADRESS 
AID UID CITY 
1 1 LONDON 

我想有输出两个结果一样,如果我进入了两个SELECT语句了一个又一个的Oracle SQL Developer中的脚本。

这是不行的,我不能指定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 

回答

1

至少有两种方式在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; 

了解更多关于variable commandexecute commandcolumn command,它是new_value clausesubstitution variables在SQL * Plus文档中 - 其中大部分也适用于SQL Developer。

演示用稍微不同的列名创建的,以避免键/保留字表:

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; 

运行的脚本,该脚本输出窗口显示:

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  

可以抑制PL/SQL procedure successfully completed消息与set feedback off,当然。

+0

亚历克斯,非常感谢您的伟大答案。绑定变量示例适合我。 NEW_VALUE谓词由Oracle SQL Developer SQL工作表编辑器标记为错误,但该脚本仍然有效。 – weberjn

+0

是的,它有一些语法标记特异性。我应该检查SD论坛,看看他们是否真的被报道过。* 8-) –