如何在SQL SELECT语句中使用包常量? [英] How to use a package constant in SQL SELECT statement?

查看:125
本文介绍了如何在SQL SELECT语句中使用包常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Oracle中的简单SELECT查询语句中使用包变量?

How can I use a package variable in a simple SELECT query statement in Oracle?

类似

SELECT * FROM MyTable WHERE TypeId = MyPackage.MY_TYPE

使用PL/SQL(在BEGIN/END中使用SELECT)完全有可能吗?

Is it possible at all or only when using PL/SQL (use SELECT within BEGIN/END)?

推荐答案

您不能.

对于要在SQL语句中使用的公共包变量,您必须编写包装函数以将值暴露给外界:

For a public package variable to be used in a SQL statement, you have to write a wrapper function to expose the value to the outside world:

SQL> create package my_constants_pkg
  2  as
  3    max_number constant number(2) := 42;
  4  end my_constants_pkg;
  5  /

Package created.

SQL> with t as
  2  ( select 10 x from dual union all
  3    select 50 from dual
  4  )
  5  select x
  6    from t
  7   where x < my_constants_pkg.max_number
  8  /
 where x < my_constants_pkg.max_number
           *
ERROR at line 7:
ORA-06553: PLS-221: 'MAX_NUMBER' is not a procedure or is undefined

创建包装函数:

SQL> create or replace package my_constants_pkg
  2  as
  3    function max_number return number;
  4  end my_constants_pkg;
  5  /

Package created.

SQL> create package body my_constants_pkg
  2  as
  3    cn_max_number constant number(2) := 42
  4    ;
  5    function max_number return number
  6    is
  7    begin
  8      return cn_max_number;
  9    end max_number
 10    ;
 11  end my_constants_pkg;
 12  /

Package body created.

现在它可以工作了:

SQL> with t as
  2  ( select 10 x from dual union all
  3    select 50 from dual
  4  )
  5  select x
  6    from t
  7   where x < my_constants_pkg.max_number()
  8  /

         X
----------
        10

1 row selected.

这篇关于如何在SQL SELECT语句中使用包常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆