Oracle - SELECT语句中的绑定变量

时间:2016-03-04 02:39:25

标签: oracle sqlplus

我的Oracle数据库中有表格

PROJECTINFO
NAME       SCHEMA
--------------------------
Test       W_TEST_000

SAMPLESET 
NAME          SS_ID
--------------------------
Test_SSet     1049
在我的SQL * Plus脚本中,

有一个替换变量(直接设置或来自用户输入)

DEFINE Project_Name = 'Test'
DEFINE SampleSet_Name = 'Test_SSet'

现在我需要另外两个绑定变量

VAR Project_Schema varchar2(50)
VAR SampleSet_ID number

然后我需要将SELECT语句的结果放入两个绑定变量

SELECT SCHEMA INTO :Project_Schema FROM PROJECTINFO WHERE NAME = '&Project_Name';
SELECT SS_ID INTO :SampleSet_ID from SAMPLESET WHERE NAME = '&SampleSet_Name';

现在我需要在:Project_Schema子表的SELECT语句中使用:SampleSet_IDW_TEST_000.MY_TABLE,如下所示:

SELECT NAME FROM :Project_Schema.MY_TABLE WHERE SS_ID = :SampleSet_ID

但这不起作用..(ORA-00903:表名无效)

如何在同一SQL * Plus脚本中的未来SQL请求中使用绑定变量?

1 个答案:

答案 0 :(得分:1)

如果将选择封装在PL / SQL块中,它将起作用,例如

DEFINE Project_Name = 'Test'
DEFINE SampleSet_Name = 'Test_SSet'

VAR Project_Schema varchar2(50)
VAR SampleSet_ID number


begin
  SELECT SCHEMA 
    INTO :Project_Schema 
    FROM PROJECTINFO 
   WHERE NAME = '&Project_Name';
end;
/
begin
  SELECT SS_ID 
    INTO :SampleSet_ID 
    from SAMPLESET 
   WHERE NAME = '&SampleSet_Name';
end;
/        

 --test the contents of the variable
Select :SampleSet_ID, :Project_Schema from dual;