在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最重要的使用。

存储过程用作脚本。它们为您运行一系列命令,您可以安排它们在特定时间运行。通常运行多个DML语句,如INSERT, UPDATE, DELETE等,甚至是SELECT。

函数用作方法。你给它传递一些东西,它会返回一个结果。应该是小而快速的-在飞行中。通常在SELECT语句中使用。

要决定何时使用以下几点可能会有所帮助-

存储过程不能返回表变量,而函数可以这样做。 您可以使用存储过程来更改服务器环境参数,而使用函数则不能。

干杯

当你想要计算并返回一个值以供其他SQL语句使用时,编写一个用户定义函数;当您想要编写存储过程时,您可以将一组可能很复杂的SQL语句分组。毕竟,这是两个非常不同的用例!

我知道这是一个非常老的问题,但是我在任何答案中都没有看到一个关键的方面:内联到查询计划中。

函数可以是…

标量: 创建函数…返回scalar_type AS BEGIN…结束 Multi-statement表值: 创建函数…返回@r表(…)开始…结束 内联表值: 创建函数…返回表作为return select…

第三种(内联表值)被查询优化器本质上视为(参数化)视图,这意味着从查询中引用函数类似于复制粘贴函数的SQL主体(而不是实际的复制粘贴),导致以下好处:

查询计划器可以优化内联函数的执行,就像它会优化任何其他子查询一样(例如,消除未使用的列,下推谓词,选择不同的JOIN策略等)。 组合几个内联函数并不需要在将第一个函数的结果提供给下一个函数之前实现它。

上述方法可能会带来潜在的显著性能节省,特别是在组合多个级别的功能时。


注意:看起来SQL Server 2019也将引入某种形式的标量函数内联。