一般来说,我们都听说过编程语言中的函数或过程。然而,我发现我几乎可以互换地使用这些术语(这可能是非常错误的)。
我的问题是:
它们的功能、目的和用途有什么不同?
请举例说明。
一般来说,我们都听说过编程语言中的函数或过程。然而,我发现我几乎可以互换地使用这些术语(这可能是非常错误的)。
我的问题是:
它们的功能、目的和用途有什么不同?
请举例说明。
当前回答
基本的不同点
函数必须返回一个值,但在存储过程中它是可选的:一个过程可以返回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标准没有谈论过程,只有函数。
在程序内部我们可以使用DML(插入/更新/删除)语句,但在函数内部我们不能使用DML语句。
过程可以同时有输入/输出参数,但函数只能有输入参数。
在存储过程中可以使用Try-Catch块,但在函数中不能使用Try-Catch块。
在选择语句中不能使用存储过程,但在函数中可以使用。
存储过程可以返回0或n个值(最多1024个),但函数只能返回1个必须的值。
存储过程不能从函数调用,但可以从存储过程调用函数。
在存储过程中可以使用事务,但在函数中不能使用事务。
我们不能在Where/Having/select部分的Sql语句中使用存储过程,但可以使用in函数。
我们不能连接存储过程,但可以连接函数。
更多. .点击这里…http://dotnet-developers-cafe.blogspot.in/2013/08/difference-between-stored-procedure-and.html
如果我们在这里与语言无关,那么过程通常指定了可靠且幂等地实现某个结果所需的一系列行为。也就是说,一个过程基本上就是一个算法。
另一方面,函数是较大程序中某种程度上独立的代码段。换句话说,函数是过程的实现。
在С#/Java中,函数是返回特定值的代码块,而过程是返回void(什么都没有)的代码块。在c# /Java中,函数和过程通常都被称为方法。
//This is a function
public DateTime GetCurrentDate()
{
return DateTime.Now.Date;
}
//This is a procedure(always return void)
public void LogMessage()
{
Console.WriteLine("Just an example message.");
}
基本的不同点
函数必须返回一个值,但在存储过程中它是可选的:一个过程可以返回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.