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


当前回答

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

其他回答

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

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

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

函数和存储过程有不同的用途。虽然这不是最好的类比,但函数可以从字面上视为任何编程语言中使用的任何其他函数,但存储的proc更像是单个程序或批处理脚本。

函数通常有一个输出和可选的输入。输出可以作为另一个函数的输入(SQL Server内置的,如DATEDIFF, LEN等)或作为SQL查询的谓词-例如,SELECT a, b, dbo.MyFunction(c) FROM表或SELECT a, b, c FROM表WHERE a = dbo.MyFunc(c)。

Stored proc用于将SQL查询绑定到事务中,并与外部世界进行交互。框架,如ADO。NET等不能直接调用函数,但可以直接调用存储过程。

函数确实有一个隐患:它们可能被误用并导致相当严重的性能问题:考虑以下查询:

SELECT * FROM dbo.MyTable WHERE col1 = dbo.MyFunction(col2)

其中MyFunction声明为:

CREATE FUNCTION MyFunction (@someValue INTEGER) RETURNS INTEGER
AS
BEGIN
   DECLARE @retval INTEGER

   SELECT localValue 
      FROM dbo.localToNationalMapTable
      WHERE nationalValue = @someValue

   RETURN @retval
END

这里发生的事情是,MyFunction函数被MyTable表中的每一行调用。如果MyTable有1000行,那么就有另外1000个针对数据库的特别查询。类似地,如果函数在列规范中指定时被调用,则该函数将对SELECT返回的每一行被调用。

所以写函数的时候一定要小心。如果从函数中的表执行SELECT操作,则需要问问自己,在父进程中使用JOIN或其他SQL构造(如CASE…当……其他的……结束)。

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

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

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

函数可以在选择语句中使用,而过程则不能。 存储过程同时接受输入和输出参数,而函数只接受输入参数。 函数不能返回text, ntext, image和时间戳类型的值,而过程可以。 函数可以在创建表中作为用户定义的数据类型使用,但过程不能。

***例如:-create table <tablename>(name varchar(10),salary getsal(name))

这里getsal是一个用户定义的函数,它返回一个工资类型,当创建表时,没有存储空间分配给工资类型,getsal函数也不执行,但当我们从这个表中获取一些值时,getsal函数get被执行,返回 类型作为结果集返回。