如何以最简单的方式在SQL Developer中的Oracle SQL脚本中定义和使用变量

时间:2018-07-03 20:03:36

标签: sql oracle oracle-sqldeveloper

我只想在SQL Developer(版本18.1.0.095)中的Oracle SQL中定义然后使用一个变量(背景:我们有一些旧的生产SQL脚本,这些脚本定期通过jBPM运行)。

在SQL Developer中,我要避免显示“输入绑定”提示窗口。

令人惊讶的是,我发现这并不是那么简单。我是否缺少明显的东西?

CREATE TABLE Test_Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255)
);

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(1,'LN_1','FN_1');

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(2,'LN_2','FN_2');

commit;

// --- method 1: not working and shows the prompt window (which I try to avoid)--------
var last_name_input varchar2(20);
select 'LN_2' into :last_name_input from dual;
select * from Test_Persons tp where tp.LASTNAME = :last_name_input;

// --- method 2: not working and shows the prompt window (which I try to avoid) --------
declare
    var last_name_input varchar2(20);
    var first_name_output varchar2(20);
begin
    select 'LN_2' into :last_name_input from dual;
    select tp.FIRSTNAME into first_name_output from Test_Persons tp where tp.LASTNAME = :last_name_input;
--    dbms_output.Put_line('here: ' || :first_name_output);
end;

// --- method 3: working and shows the prompt window (which I try to avoid) --------
var last_name_input varchar2(20);
exec :last_name_input := 'LN_2';
select * from Test_Persons tp where tp.LASTNAME = :last_name_input;

2 个答案:

答案 0 :(得分:1)

在Oracle 12c上删除“:”后,您的method2可以工作-

CREATE TABLE Test_Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255)
);

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(1,'LN_1','FN_1');

INSERT INTO Test_Persons
    (PersonID,LastName,FirstName)
    values(2,'LN_2','FN_2');

commit;


set serverout on;

declare
    last_name_input varchar2(20);
    first_name_output varchar2(20);
begin
    select 'LN_2' into last_name_input from dual;
    select tp.FIRSTNAME into first_name_output from Test_Persons tp where tp.LASTNAME = last_name_input;
    dbms_output.Put_line('here: ' || first_name_output);
end;

输出-

Table TEST_PERSONS created.


1 row inserted.


1 row inserted.


Commit complete.

here: FN_2


PL/SQL procedure successfully completed.

答案 1 :(得分:1)

您可以使用这两种方法中的任一种来避免在SQL Developer中出现提示。

exec设置变量的值,并以脚本( F5 )的身份运行

var   last_name_input varchar2(20);
EXEC  :last_name_input := 'LN_2'
select * from Test_Persons tp where tp.LASTNAME = :last_name_input;

另一种方法是使用替换变量(默认情况下为&,也可以使用SET DEFINE对其进行更改

define last_name_input = 'LN_2'
select * from Test_Persons tp where tp.LASTNAME = '&last_name_input';