【问题标题】:Use of Variables for Multiple Independent PL SQL Queries对多个独立 PL SQL 查询使用变量
【发布时间】:2014-08-11 09:47:05
【问题描述】:

我有一个 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;

这里的问题是,我可以使用一个用户提示并将用户输入用于所有三个查询吗?我确实尝试将 && 用于后续变量,但这会使用户输入在整个会话中保持活动状态。我可能需要多次运行此脚本。

【问题讨论】:

    标签: sql oracle sqlplus substitution


    【解决方案1】:

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

    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    
      

    【讨论】:

    • 非常感谢尼古拉斯。那很快! :)
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2021-08-03
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多