给出两个表
USERS
UID NAME
1 KEN
ADRESS
AID UID CITY
1 1 LONDON
我希望有一个Oracle SQL Developer脚本输出两个结果表,就像我已经一个接一个地输入两个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
答案 0 :(得分: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;
详细了解SQL * Plus文档中的variable
command,execute
command,column
command及其new_value
clause和substitution variables - 其中大部分内容也适用于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
消息。