如何在 SQL SELECT 语句中使用包常量?
如何在 Oracle 中的简单 SELECT 查询语句中使用包变量?
像这样的事情
SELECT * FROM MyTable WHERE TypeId = MyPackage.MY_TYPE
是否可能完全或仅在使用 PL/SQL 时(在 BEGIN/END 中使用 SELECT)?
How can I use a package variable in a simple SELECT query statement in Oracle?
Something like
SELECT * FROM MyTable WHERE TypeId = MyPackage.MY_TYPE
Is it possible at all or only when using PL/SQL (use SELECT within BEGIN/END)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。
对于要在 SQL 语句中使用的公共包变量,您必须编写一个包装函数以将值公开给外界:
创建一个包装函数:
现在它可以工作了:
You can't.
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:
Create a wrapper function:
And now it works:
有一种更通用的方法对我来说效果很好。您使用输入常量名称(即 schema.package.constantname)创建一个函数,它会返回常量值。您可以通过绑定 res 变量来立即执行 PL/SQL 块(请参见示例)。
函数如下所示:
然后,您可以在任何 SQL 中使用任何包的常量,即像
这样,您只需要 1 个函数,并且可以利用现有的 packages.constants 的优势。
There is a more generic way which works fine for me. You create a function with input constant name (i.e. schema.package.constantname) and it returns you the constant value. You make use of executing immediate a PL/SQL block by binding res variable (see example).
Function looks like this:
You can then use the constant of any package in any SQL, i.e. like
Like this you need only 1 function and you take the advantage to use existing packages.constants.
注意:我只在 Oracle 11g 中尝试过此操作。
我有类似的需求,发现简单地声明一个函数(不带包)来返回所需的值更容易。要将它们放入 ddl 中进行导入,请记住用 / 字符分隔每个函数声明。例如:
这允许您像引用常量值一样引用该函数(例如,您甚至不需要括号)。
例如(注意 to_char 方法显示精度已被保留):
SQL>从 Dual 中选择 undefined_int;
SQL>从对偶中选择未定义的字符串;
SQL>从对偶中选择 undefined_double;
SQL>从 Dual 中选择 to_char(undefined_double,'9.999999999999999EEEE') ;
SQL>从 Dual 中选择 to_char(undefined_double,'9.99999999999999999EEEE') ;
Note: I only tried this in Oracle 11g.
I had a similar need and found it easier to simply declare a function (without the package) to return the desired value. To put these in ddl for import, remember to separate each function declaration with the / character. For example:
This allows you to reference the function as though it was a constant value (e.g., you don't even need the parentheses).
For example (note the to_char methods to show the precision has been preserved):
SQL> select undefined_int from dual;
SQL> select undefined_string from dual;
SQL> select undefined_double from dual;
SQL> select to_char(undefined_double,'9.999999999999999EEEE') from dual;
SQL> select to_char(undefined_double,'9.99999999999999999EEEE') from dual;
不,你不能这样做。您需要提供一个返回值的函数,然后在 SQL 中使用它:
No, you aren'e allowed to do that. You would need to provide a function that returns the value and then use that in the SQL: