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


当前回答

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

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

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

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

其他回答

函数是计算值,不能对SQL Server执行永久的环境更改(即不允许INSERT或UPDATE语句)。

如果函数返回标量值,则可以在SQL语句中使用它;如果函数返回结果集,则可以连接它。

从总结答案的评论中,有一点值得注意。感谢@Sean K Anderson:

函数遵循计算机科学的定义,即它们必须返回一个值,并且不能更改作为参数接收的数据 (论点)。函数不允许改变任何东西,必须 至少有一个参数,并且它们必须返回一个值。存储 Procs不需要有参数,可以改变数据库对象, 并且不需要返回值。

存储过程与用户自定义函数的区别:

Stored procedures cannot be used in Select statements. Stored procedures support Deferred Name Resolution. Stored procedures are generally used for performing business logic. Stored procedures can return any datatype. Stored procedures can accept greater numbers of input parameter than user defined functions. Stored procedures can have up to 21,000 input parameters. Stored procedures can execute Dynamic SQL. Stored procedures support error handling. Non-deterministic functions can be used in stored procedures.


User-defined functions can be used in Select statements. User-defined functions do not support Deferred Name Resolution. User-defined functions are generally used for computations. User-defined functions should return a value. User-defined functions cannot return Images. User-defined functions accept smaller numbers of input parameters than stored procedures. UDFs can have up to 1,023 input parameters. Temporary tables cannot be used in user-defined functions. User-defined functions cannot execute Dynamic SQL. User-defined functions do not support error handling. RAISEERROR OR @@ERROR are not allowed in UDFs. Non-deterministic functions cannot be used in UDFs. For example, GETDATE() cannot be used in UDFs.

在SQL Server中,函数和存储过程是两种不同类型的实体。

函数:在SQL Server数据库中,函数用于执行一些动作,动作立即返回结果。 函数有两种类型:

系统定义的 用户定义的

存储过程:在SQL Server中,存储过程存储在服务器中,它可以返回零,单个和多个值。 存储过程有两种类型:

系统存储过程 用户自定义过程

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

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

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

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