对多个独立PL SQL查询使用变量

时间:2014-08-11 09:47:05

标签: sql oracle sqlplus substitution

我有一个PL / SQL脚本Test.sql,其中包含三个独立的查询。

的Test.sql

SELECT ABC.* 
  FROM Student ABC, Teacher BCD
 WHERE 1=1
   AND ABC.Period = &Period 
   AND ABC.StudentID = BCD.StudentID;


SELECT ABC.CandidateID 
  from Student ABC
 where not exists(
                  select 1
                    from Teacher BCD
                   where ABC.StudentID = BCD.StudentID
                     AND ABC.Period = &&Period
                 ); 


SELECT BCD.CandidateID 
  from Teacher BCD
 where not exists (
                   select 1
                     from Student ABC
                    where ABC.StudentID = BCD.StudentID
                  )
   AND ABC.Period = &&Period;

问题是,我可以使用一个用户提示并使用用户输入来查看所有三个查询吗?我确实试过使用&&对于后续变量,但保持用户输入对整个会话有效。我可能需要多次运行此脚本。

1 个答案:

答案 0 :(得分:2)

第一次使用&&varname时,只有在重新启动SQL * PLUS而不是会话时,才会定义替换变量并使其未定义。因此,如果您希望每次运行脚本时SQL * PLUS都提示您输入新值,您可以undefine变量并使用双符号运行变量名前面的脚本,或使用{{3}命令。这是一个例子:

  1. 使用undefine命令:

    undefine period
    
    -- precede variable name with double ampersand(variable gets defined)  
    -- the first time you reference it in a query.
    -- In subsequent references the variable can be preceded with 
    -- single ampersand.
    ...
    and ABC.Period = &&Period  
    
    ...
    and ABC.Period = &Period
    
  2. 使用accept命令定义<<variable_name>>替换变量:

    accept period number prompt 'Input period: '
    
    -- now you can reference `period` substitution variable
    -- in your script prefixing its name with ampersand sign
    
    ...
    and ABC.Period = &period    
    
相关问题