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


当前回答

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

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

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

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

其他回答

SQL Server函数,比如游标,是你最后的武器!它们确实存在性能问题,因此应该尽可能避免使用表值函数。谈论性能就是谈论一个有超过1,000,000条记录的表托管在一个中产阶级硬件的服务器上;否则,您不需要担心函数对性能的影响。

永远不要使用函数将结果集返回给外部代码(如ADO.Net) 尽可能使用视图/存储procs组合。您可以使用DTA(数据库调优顾问)给您的建议(比如索引视图和统计数据)来解决未来的增长性能问题——有时!

如需进一步参考,请参阅:http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

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

SELECT a, lookupValue(b), c FROM customers 

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

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

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

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

STORE PROCEDURE FUNCTION (USER DEFINED FUNCTION)
Procedure can return 0, single or multiple values Function can return only single value
Procedure can have input, output parameters Function can have only input parameters
Procedure cannot be called from a function Functions can be called from procedure
Procedure allows select as well as DML statement in it Function allows only select statement in it
Exception can be handled by try-catch block in a procedure Try-catch block cannot be used in a function
We can go for transaction management in procedure We can not go for transaction management in function
Procedure cannot be utilized in a select statement Function can be embedded in a select statement
Procedure can affect the state of database means it can perform CRUD operation on database Function can not affect the state of database means it can not perform CRUD operation on database
Procedure can use temporary tables Function can not use temporary tables
Procedure can alter the server environment parameters Function can not alter the environment parameters
Procedure can use when we want instead is to group a possibly- complex set of SQL statements Function can use when we want to compute and return a value for use in other SQL statements

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

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

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

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

一般来说,使用存储过程的性能更好。 例如,在以前版本的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