功能、程序和触发器 - 它们有何不同以及何时使用?
我对 Oracle PL/SQL 非常陌生...
Oracle 函数、过程和过程之间有什么区别?触发器?每种的适当用途是什么?
I am very new to Oracle PL/SQL...
What is the difference between Oracle Functions, Procedure & Triggers? And what are appropriate uses of each?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上只是你随意运行的一段代码。在任何语言中,函数都会返回一个值(例如“更新的行数、字符串等”),而过程不会返回任何值。
触发器可以而且可能会使用函数和过程。
basically just a piece of code that you run at will. In any language Function will return a value (eg' number of rows updated, a string etc') and a Procedure will not return any value.
A trigger can and probably will use functions and procedures.
这三种都是不同类型的 PL/SQL 块,这意味着您可以对多个 SQL 语句进行分组并使用变量、异常块等。过程和函数特别有助于重用,这样您就不必在多个位置编写相同的逻辑,并且您可以授予某人/某些应用程序访问“做某事”或“获取某些值”的权限,但不访问表直接地。
最好用不同的用例来解释差异。
让我们考虑一下客户下订单的简单情况。
所下的每个订单都将包含一系列步骤,因此您可以使用PL/SQL 块来完成该工作(执行一组 SQL 语句)。程序是实现这一点的方法。
假设总税计算基于一系列条件,您可以(并且应该)通过调用函数来避免在多个位置编写逻辑。函数只能返回一个值,这正是大多数情况下您所需要的。如果需要返回多个值,可以使用过程和输出参数。
使用触发器的原因完全不同。如果您想在满足某些条件(触发事件)时执行一组语句,触发器可能是您的解决方案。
您可以在下面的链接中了解有关其用例的更多信息。请注意,通常情况下,Oracle 功能(如审核、版本控制)等已经就位,因此您不必使用触发器重新实现它。确保在开发解决方案之前进行研究,尤其是使用触发器。
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/triggers.htm#i1006211
All three are different types of PL/SQL Blocks, which means that you can group multiple SQL statements and use variables, exception blocks so on. Procedures and functions in particular help re-use, so that you don't have to write the same logic at multiple places and you can grant someone/some application access to "do something" or "get some value" but not access the tables directly.
It is probably better to explain the difference with different use cases.
Let's consider the simple case of a customer placing an order.
Every order that is placed will have a series of steps, so you can have a PL/SQL Block that does that work (executes a set of sql statements). A procedure is the way to implement this.
Let's assume the total tax calculation is based on series of conditions, you can (and should) avoid coding the logic at multiple places by calling a function instead. A function can return only one value, which is what you need in most cases. If you need more than one value to be returned, you can use a procedure and out parameters.
Triggers are used for a completely different reason. If you want to execute a set of statements when some condition is met (triggering event), trigger might be your solution.
You can read more about their use cases in the link below. Please note that more often than not, there is an oracle feature (like auditing, versioning) etc, which is already in place so that you don't have to re implement it using triggers. Make sure you research before developing a solution, particularly using triggers.
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/triggers.htm#i1006211