在SQL中什么时候应该使用函数而不是存储过程,反之亦然?每一个的目的是什么?


当前回答

It is mandatory for Function to return a value while it is not for stored procedure. Select statements only accepted in UDF while DML statements not required. Stored procedure accepts any statements as well as DML statements. UDF only allows inputs and not outputs. Stored procedure allows for both inputs and outputs. Catch blocks cannot be used in UDF but can be used in stored procedure. No transactions allowed in functions in UDF but in stored procedure they are allowed. Only table variables can be used in UDF and not temporary tables. Stored procedure allows for both table variables and temporary tables. UDF does not allow stored procedures to be called from functions while stored procedures allow calling of functions. UDF is used in join clause while stored procedures cannot be used in join clause. Stored procedure will always allow for return to zero. UDF, on the contrary, has values that must come - back to a predetermined point.

其他回答

用户定义函数是sql server程序员可用的重要工具。您可以像这样在SQL语句中内联使用它

SELECT a, lookupValue(b), c FROM customers 

其中lookupValue将是UDF。这种功能在使用存储过程时是不可能实现的。同时,您不能在UDF中做某些事情。这里要记住的基本事情是UDF的:

不能产生永久的变化 无法更改数据

存储过程可以做这些事情。

对我来说,UDF的内联使用是UDF最重要的使用。

这里有一个更喜欢函数而不是存储过程的实际原因。如果有一个存储过程需要另一个存储过程的结果,则必须使用insert-exec语句。这意味着您必须创建一个临时表并使用exec语句将存储过程的结果插入到临时表中。它是混乱的。这样做的一个问题是insert-execs不能嵌套。

如果您使用调用其他存储过程的存储过程,可能会遇到这种情况。如果嵌套存储过程只是返回一个数据集,则可以将其替换为表值函数,这样就不会再出现此错误。

(这是我们应该将业务逻辑排除在数据库之外的另一个原因)

下面是一个总结差异的表格:

Stored Procedure Function
Returns Zero or more values A single value (which may be a scalar or a table)
Can use transaction? Yes No
Can output to parameters? Yes No
Can call each other? Can call a function Cannot call a stored procedure
Usable in SELECT, WHERE and HAVING statements? No Yes
Supports exception handling (via try/catch)? Yes No

一般来说,使用存储过程的性能更好。 例如,在以前版本的SQL Server中,如果你将函数置于JOIN条件下,基数估计为1 (SQL 2012之前)和100 (SQL 2012之后和SQL 2017之前),引擎可能会生成一个糟糕的执行计划。

此外,如果你把它放在WHERE子句中,SQL引擎可能会生成一个糟糕的执行计划。

在SQL 2017中,微软引入了称为交错执行的功能,以产生更准确的估计,但存储过程仍然是最佳解决方案。

要了解更多细节,请参阅以下Joe Sack的文章 https://techcommunity.microsoft.com/t5/sql-server/introducing-interleaved-execution-for-multi-statement-table/ba-p/385417

从返回单个值的函数开始。这样做的好处是,您可以将经常使用的代码放入函数中,并将它们作为结果集中的列返回。

然后,可以使用一个函数来表示参数化的城市列表。getcitiesin ("NY")返回一个可以用作连接的表。

这是一种组织代码的方式。知道什么时候是可重用的,什么时候是浪费时间,只有通过试验、错误和经验才能获得。

此外,函数在SQL Server中也是一个好主意。它们速度更快,功能也相当强大。内联和直接选择。注意不要过度使用。