首页 > 解决方案 > 如何在 Oracle PL-SQL(或 sql-plus)的某些选择语句中使用变量

问题描述

我有一些选择语句,它们都需要使用相同的变量。那我能不能先定义一个变量,然后在下面的语句中直接使用,像这样:

declare variable;  -- a to_date function
select statement 1;
select statement 2;
select statement 3;
...

所以当条件改变时,我可以修改变量。如何在 oracle 中使用 pl-sql(或 sql-plus)来完成它?

标签: oracleselectplsqlsqlplus

解决方案


您需要简单的 sql*plus 变量。

variable my_date varchar2(30)

exec :my_date := '01-oct-2019';

select * from t where date_col = to_date(:my_date,'dd-mon-yyyy');

-- other select statements

您也可以使用替换变量来实现这一点。

select * from t1 where date_col = to_date(&&my_date,'dd-mon-yyyy');

select * from t2 where date_col = to_date(&&my_date,'dd-mon-yyyy');

-- other select statements using &&my_date

在这里,oracle 将提示my_date一次(因为我们使用了两个&),并且它的值将用于该会话的所有 select 语句。

干杯!!


推荐阅读