gpt4 book ai didi

sql - 如何在 SQL SELECT 语句中使用包常量?

转载 作者:行者123 更新时间:2023-12-04 13:20:44 24 4
gpt4 key购买 nike

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

就像是

SELECT * FROM MyTable WHERE TypeId = MyPackage.MY_TYPE

是否有可能或仅在使用 PL/SQL 时(在 BEGIN/END 中使用 SELECT)?

最佳答案

你不能。

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

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 - 如何在 SQL SELECT 语句中使用包常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5178830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com