SQL 使用可选参数创建过程的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35124024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:22:34  来源:igfitidea点击:

Ways to create a procedure with optional parameters?

sqloracleplsql

提问by nicklowkc

Is that possible to create a procedure with optional parameters? For example, create a procedure that add up all of the parameters.

是否可以创建带有可选参数的过程?例如,创建一个将所有参数相加的过程。

add(n1, n2, .... nn)

Another procedure like for example I have 11 parameters, it adds up from 1 to 10, and the last parameter can do something else. By googling, it seems like you can use array to do it, but most of the results I got was about another programming languages, not plsql. If apply the theory to plsql I guess I suppose to use varray or nested table?

另一个程序,例如我有 11 个参数,它从 1 到 10 加起来,最后一个参数可以做其他事情。通过谷歌搜索,您似乎可以使用数组来做到这一点,但我得到的大部分结果都是关于另一种编程语言,而不是 plsql。如果将理论应用于 plsql 我想我想使用 varray 或嵌套表?

采纳答案by Ilia Maskov

You can do this by DEFAULToperator or '='

您可以通过DEFAULT运算符或“=”来执行此操作

PROCEDURE ADD(NUMBER n1, NUMBER n2, NUMBER n3 DEFAULT 0)....

http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/fundamentals.htm#CHDFADII

http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/fundamentals.htm#CHDFADII

If you want to use it without explicit parameter naming in calls then you have to place your optional parameters at the end of the procedure signature list. With explicit parameter naming in call they can be placed anywhere

如果您想在调用中没有显式参数命名的情况下使用它,那么您必须将可选参数放在过程签名列表的末尾。通过调用中的显式参数命名,它们可以放置在任何地方

回答by Dmitriy

You need to declare parameter with default value:

您需要使用默认值声明参数:

procedure add (n1 number, 
               n2 number default 0,
               ...
               nn number default 99) is ...

Using this procedure:

使用此程序:

begin
  add(1);
  add(5, 6, 7, ..., 111);
  add(n1 => 111, n5 => 345, nn => 17);
end;

In last case, as you can see, you can pass values for 3 parameters (n1, n5, nn), for others parameters default values will be used.

在最后一种情况下,如您所见,您可以为 3 个参数 ( n1, n5, nn)传递值,其他参数将使用默认值。