一般来说,我们都听说过编程语言中的函数或过程。然而,我发现我几乎可以互换地使用这些术语(这可能是非常错误的)。

我的问题是:

它们的功能、目的和用途有什么不同?

请举例说明。


当前回答

在db的上下文中: 存储过程是预编译的执行计划,而as函数不是。

其他回答

在大多数情况下:函数返回一个值,而过程不返回。两者都是组合在一起做相同事情的代码片段。

在函数式编程上下文中(所有函数都返回值),函数是一个抽象对象:

f(x)=(1+x)
g(x)=.5*(2+x/2)

这里,f和g是同一个函数,但是过程不同。

函数返回值,过程只执行命令。

函数的名称来源于数学。它用于根据输入计算一个值。

过程是一组可以按顺序执行的命令。

在大多数编程语言中,甚至函数也可以有一组命令。因此,差值只是返回一个值。

但是如果你想让函数保持简洁(看看函数式语言就知道了),你需要确保函数没有副作用。

基本的不同点

函数必须返回一个值,但在存储过程中它是可选的:一个过程可以返回0或n个值。 函数只能有输入参数,而过程可以有输入/输出参数。 对于一个函数,必须带一个输入参数,但存储过程可以带0到n个输入参数。 函数可以从过程中调用,而过程不能从函数中调用。

先进的差异

异常可以用try-catch块在过程中处理,而try-catch块不能在函数中使用。 我们可以在过程中使用事务管理,而在函数中则不能。

在SQL:

A Procedure allows SELECT as well as DML (INSERT, UPDATE, DELETE) statements in it, whereas Function allows only SELECT statement in it. Procedures can not be utilized in a SELECT statement, whereas Functions can be embedded in a SELECT statement. Stored Procedures cannot be used in SQL statements anywhere in a WHERE (or a HAVING or a SELECT) block, whereas Functions can. Functions that return tables can be treated as another Rowset. This can be used in a JOIN block with other tables. Inline Functions can be thought of as views that take parameters and can be used in JOIN blocks and other Rowset operations.

C语言示例:

// function
int square( int n ) {
   return n * n;
}

// procedure
void display( int n ) {
   printf( "The value is %d", n );
}

尽管你应该注意到C标准没有谈论过程,只有函数。

一般来说,程序是一系列指令。 函数可以是相同的,但它通常返回一个结果。