SQL Server 中的函数与存储过程

发布于 2024-07-29 17:43:24 字数 48 浏览 8 评论 0原文

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

When should I use a function rather than a stored procedure in SQL, and vice versa? What is the purpose of each?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

海未深 2024-08-05 17:43:24

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

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

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

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

Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e., no INSERT or UPDATE statements allowed).

A function can be used inline in SQL statements if it returns a scalar value or can be joined upon if it returns a result set.

A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:

Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters
(the arguments). Functions are not allowed to change anything, must
have at least one parameter, and they must return a value. Stored
procs do not have to have a parameter, can change database objects,
and do not have to return a value.

空城仅有旧梦在 2024-08-05 17:43:24

下表总结了这些差异:

存储过程函数
返回零个或多个值单个值(可以是标量或表)
可以使用事务吗?
可以输出到参数吗?
可以互相打电话吗?可以调用函数不能调用存储过程
可在 SELECT、WHERE 和 HAVING 语句中使用吗?
支持异常处理(通过 try/catch)?

Here's a table summarizing the differences:

Stored ProcedureFunction
ReturnsZero or more valuesA single value (which may be a scalar or a table)
Can use transaction?YesNo
Can output to parameters?YesNo
Can call each other?Can call a functionCannot call a stored procedure
Usable in SELECT, WHERE and HAVING statements?NoYes
Supports exception handling (via try/catch)?YesNo
素年丶 2024-08-05 17:43:24

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

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

存储过程用于在事务中将 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

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

所以你在编写函数时确实需要小心。 如果您在函数中从表中执行 SELECT,您需要问自己是否可以通过父存储过程中的 JOIN 或其他一些 SQL 构造(例如 CASE ... WHEN ... ELSE ...结尾)。

Functions and stored procedures serve separate purposes. Although it's not the best analogy, functions can be viewed literally as any other function you'd use in any programming language, but stored procs are more like individual programs or a batch script.

Functions normally have an output and optionally inputs. The output can then be used as the input to another function (a SQL Server built-in such as DATEDIFF, LEN, etc) or as a predicate to a SQL Query - e.g., SELECT a, b, dbo.MyFunction(c) FROM table or SELECT a, b, c FROM table WHERE a = dbo.MyFunc(c).

Stored procs are used to bind SQL queries together in a transaction, and interface with the outside world. Frameworks such as ADO.NET, etc. can't call a function directly, but they can call a stored proc directly.

Functions do have a hidden danger though: they can be misused and cause rather nasty performance issues: consider this query:

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

Where MyFunction is declared as:

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

   SELECT localValue 
      FROM dbo.localToNationalMapTable
      WHERE nationalValue = @someValue

   RETURN @retval
END

What happens here is that the function MyFunction is called for every row in the table MyTable. If MyTable has 1000 rows, then that's another 1000 ad-hoc queries against the database. Similarly, if the function is called when specified in the column spec, then the function will be called for each row returned by the SELECT.

So you do need to be careful writing functions. If you do SELECT from a table in a function, you need to ask yourself whether it can be better performed with a JOIN in the parent stored proc or some other SQL construct (such as CASE ... WHEN ... ELSE ... END).

哥,最终变帅啦 2024-08-05 17:43:24

存储过程和用户​​定义函数的区别:

  • 存储过程不能在 Select 语句中使用。
  • 存储过程支持延迟名称解析。
  • 存储过程通常用于执行业务逻辑。
  • 存储过程可以返回任何数据类型。
  • 存储过程可以比用户定义的函数接受更多数量的输入参数。 存储过程最多可以有 21,000 个输入参数。
  • 存储过程可以执行动态SQL。
  • 存储过程支持错误处理。
  • 非确定性函数可以在存储过程中使用。

  • 用户定义的函数可以在 Select 语句中使用。
  • 用户定义的函数不支持延迟名称解析。
  • 用户定义的函数通常用于计算。
  • 用户定义的函数应该返回一个值。
  • 用户定义的函数无法返回图像。
  • 用户定义的函数比存储过程接受更少数量的输入参数。 UDF 最多可以有 1,023 个输入参数。
  • 临时表不能在用户定义的函数中使用。
  • 用户定义的函数无法执行动态 SQL。
  • 用户定义的函数不支持错误处理。 UDF 中不允许使用 RAISEERROR@@ERROR
  • 非确定性函数不能在 UDF 中使用。 例如,GETDATE() 不能在 UDF 中使用。

Differences between stored procedures and user-defined functions:

  • 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.
樱桃奶球 2024-08-05 17:43:24
存储过程函数(用户定义函数)
过程可以返回 0、单个或多个值函数只能返回单个值
过程可以有输入、输出参数函数只能有输入参数
过程不能从函数调用函数可以从过程
调用允许在其中使用 select 以及 DML 语句函数中只允许使用 select 语句
异常可以通过过程中的 try-catch 块处理函数中不能使用 try-catch 块
我们可以在过程中进行事务管理我们不能去用于函数中的事务管理
过程不能在 select 语句中使用函数可以嵌入在 select 语句中
过程可以影响数据库的状态,意味着可以对数据库执行 CRUD 操作函数不能影响数据库的状态,意味着不能执行 CRUD 操作对数据库的操作
过程可以使用临时表函数不能使用临时表
过程可以改变服务器环境参数函数不能改变环境参数
当我们想要将一组可能复杂的 SQL 语句分组时,可以使用过程 函数可以使用 when我们想要计算并返回一个值以供其他 SQL 语句使用
STORE PROCEDUREFUNCTION (USER DEFINED FUNCTION)
Procedure can return 0, single or multiple valuesFunction can return only single value
Procedure can have input, output parametersFunction can have only input parameters
Procedure cannot be called from a functionFunctions can be called from procedure
Procedure allows select as well as DML statement in itFunction allows only select statement in it
Exception can be handled by try-catch block in a procedureTry-catch block cannot be used in a function
We can go for transaction management in procedureWe can not go for transaction management in function
Procedure cannot be utilized in a select statementFunction can be embedded in a select statement
Procedure can affect the state of database means it can perform CRUD operation on databaseFunction can not affect the state of database means it can not perform CRUD operation on database
Procedure can use temporary tablesFunction can not use temporary tables
Procedure can alter the server environment parametersFunction can not alter the environment parameters
Procedure can use when we want instead is to group a possibly- complex set of SQL statementsFunction can use when we want to compute and return a value for use in other SQL statements
一袭水袖舞倾城 2024-08-05 17:43:24

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

Write a user-defined function when you want to compute and return a value for use in other SQL statements; write a stored procedure when you want instead is to group a possibly-complex set of SQL statements. These are two pretty different use cases, after all!

风月客 2024-08-05 17:43:24

基本区别

函数必须返回一个值,但在存储过程中它是可选的(过程可以返回零个或n个值)。

函数只能有输入参数,而过程可以有输入/输出参数。

函数需要一个输入参数,这是强制性的,但存储过程可能需要 o 到 n 个输入参数。

可以从过程调用函数,但不能从函数调用过程。

高级差异

过程允许在其中使用 SELECT 以及 DML(INSERT/UPDATE/DELETE) 语句,而函数仅允许在其中使用 SELECT 语句。

过程不能在 SELECT 语句中使用,而函数可以嵌入在 SELECT 语句中。

存储过程不能在 SQL 语句中的 WHERE/HAVING/SELECT 部分中的任何位置使用,而函数可以。

返回表的函数可以被视为另一个行集。 这可以在与其他表的 JOIN 中使用。

内联函数可以被视为带有参数的视图,并且可以在 JOIN 和其他 Rowset 操作中使用。

异常可以通过过程中的 try-catch 块来处理,而 try-catch 块不能在函数中使用。

我们可以在过程中进行事务管理,但不能在函数中进行。

来源

Basic Difference

Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).

Functions can have only input parameters for it whereas Procedures can have input/output parameters .

Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..

Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.

Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.

Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.

Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.

Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.

Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.

We can go for Transaction Management in Procedure whereas we can't go in Function.

source

岁月流歌 2024-08-05 17:43:24

用户定义函数是 sql server 程序员可用的重要工具。 您可以在 SQL 语句中内联使用它,如下所示,

SELECT a, lookupValue(b), c FROM customers 

其中 lookupValue 将是 UDF。 使用存储过程时无法实现这种功能。 同时,您无法在 UDF 内执行某些操作。 这里要记住的基本事情是 UDF:

  • 无法创建永久更改
  • 无法更改数据

存储过程可以执行这些操作。

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

a User Defined Function is an important tool available to a sql server programmer. You can use it inline in a SQL statement like so

SELECT a, lookupValue(b), c FROM customers 

where lookupValue will be an UDF. This kind of functionality is not possible when using a stored procedure. At the same time you cannot do certain things inside a UDF. The basic thing to remember here is that UDF's:

  • cannot create permanent changes
  • cannot change data

a stored procedure can do those things.

For me the inline usage of a UDF is the most important usage of a UDF.

鸩远一方 2024-08-05 17:43:24

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

函数 用作方法。你向它传递一些东西,它就会返回一个结果。 应该小而快——即时执行。 通常用在 SELECT 语句中。

Stored Procedures are used as scripts. They run a series of commands for you and you can schedule them to run at certain times. Usually runs multiples DML statements like INSERT, UPDATE, DELETE, etc. or even SELECT.

Functions are used as methods. You pass it something and it returns a result. Should be small and fast - does it on the fly. Usually used in a SELECT statement.

想念有你 2024-08-05 17:43:24

SQL Server 函数(如游标)旨在用作您的最后武器! 它们确实存在性能问题,因此应尽可能避免使用表值函数。 谈论性能是指在中级硬件的服务器上托管超过 1,000,000 条记录的表; 否则您无需担心这些功能对性能造成的影响。

  1. 切勿使用函数将结果集返回到外部代码(如 ADO.Net)
  2. 尽可能使用视图/存储过程组合。 有时,您可以使用 DTA(数据库调优顾问)提供的建议(如索引视图和统计信息)从未来的增长性能问题中恢复过来!

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

SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.

  1. Never use a function to return a result-set to an external code (like ADO.Net)
  2. Use views/stored procs combination as much as possible. you can recover from future grow-performance issues using the suggestions DTA (Database Tuning Adviser) would give you (like indexed views and statistics) --sometimes!

for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

笨死的猪 2024-08-05 17:43:24

存储过程:

  • 就像SQL Server中的一个微型程序。
  • 可以像 select 语句一样简单,也可以像 long 语句一样复杂
    添加、删除、更新和/或读取多个数据的脚本
    数据库中的表。
  • (可以实现循环和游标,它们都允许您使用
    较小的结果或对数据进行逐行操作。)
  • 应使用 EXEC 或 EXECUTE 语句调用。
  • 返回表变量,但我们不能使用OUT参数。
  • 支持交易。

功能:

  • 不能用于更新、删除或向数据库添加记录。
  • 仅返回单个值或表值。
  • 只能用于选择记录。 然而,它可以被称为
    在标准 SQL 中非常容易,例如:

    SELECT dbo.functionname('参数1') 
      

    从 sysObjects 中选择名称、dbo.Functionname('Parameter1') 
      
  • 对于简单的可重用选择操作,函数可以简化代码。
    只是要小心在函数中使用 JOIN 子句。 如果你的
    函数有一个 JOIN 子句,您可以从另一个选择中调用它
    返回多个结果的语句,该函数调用将 JOIN
    结果集中返回的行的这些表在一​​起。 所以
    尽管它们有助于简化某些逻辑,但它们也可以是
    如果使用不当,就会成为性能瓶颈。

  • 使用 OUT 参数返回值。
  • 不支持交易。

Stored procedure:

  • Is like a miniature program in SQL Server.
  • Can be as simple as a select statement, or as complex as a long
    script that adds, deletes, updates, and/or reads data from multiple
    tables in a database.
  • (Can implement loops and cursors, which both allow you to work with
    smaller results or row by row operations on data.)
  • Should be called using EXEC or EXECUTE statement.
  • Returns table variables, but we can't use OUT parameter.
  • Supports transactions.

Function:

  • Can not be used to update, delete, or add records to the database.
  • Simply returns a single value or a table value.
  • Can only be used to select records. However, it can be called
    very easily from within standard SQL, such as:

    SELECT dbo.functionname('Parameter1')
    

    or

    SELECT Name, dbo.Functionname('Parameter1') FROM sysObjects
    
  • For simple reusable select operations, functions can simplify code.
    Just be wary of using JOIN clauses in your functions. If your
    function has a JOIN clause and you call it from another select
    statement that returns multiple results, that function call will JOIN
    those tables together for each line returned in the result set. So
    though they can be helpful in simplifying some logic, they can also be a
    performance bottleneck if they're not used properly.

  • Returns the values using OUT parameter.
  • Does not support transactions.
浅忆流年 2024-08-05 17:43:24

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

  1. 存储过程无法返回表变量,而 as 函数可以返回表变量。

  2. 您可以使用存储过程来更改服务器环境参数,而使用函数则不能。

干杯

To decide on when to use what the following points might help-

  1. Stored procedures can't return a table variable where as function can do that.

  2. You can use stored procedures to alter the server environment parameters where as using functions you can't.

cheers

清风无影 2024-08-05 17:43:24

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

然后,您可以使用一个函数来获取参数化的城市列表。 dbo.GetCitiesIn("NY") 返回一个可用作联接的表。

这是一种组织代码的方式。 知道什么时候某些东西可以重用,什么时候它是浪费时间,只有通过反复试验和经验才能获得。

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

Start with functions that return a single value. The nice thing is you can put frequently used code into a function and return them as a column in a result set.

Then, you might use a function for a parameterized list of cities. dbo.GetCitiesIn("NY") That returns a table that can be used as a join.

It's a way of organizing code. Knowing when something is reusable and when it is a waste of time is something only gained through trial and error and experience.

Also, functions are a good idea in SQL Server. They are faster and can be quite powerful. Inline and direct selects. Careful not to overuse.

不疑不惑不回忆 2024-08-05 17:43:24

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

如果您受困于调用其他存储过程的存储过程,则可能会遇到这种情况。 如果嵌套存储过程仅返回数据集,则可以将其替换为表值函数,并且您将不再收到此错误。

这是我们应该将业务逻辑保留在数据库之外的另一个原因

Here's a practical reason to prefer functions over stored procedures. If you have a stored procedure that needs the results of another stored procedure, you have to use an insert-exec statement. This means that you have to create a temp table and use an exec statement to insert the results of the stored procedure into the temp table. It's messy. One problem with this is that insert-execs cannot be nested.

If you're stuck with stored procedures that call other stored procedures, you may run into this. If the nested stored procedure simply returns a dataset, it can be replaced with a table-valued function and you'll no longer get this error.

(this is yet another reason we should keep business logic out of the database)

难得心□动 2024-08-05 17:43:24

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

函数可以是...

  1. 标量:

    CREATE FUNCTION ... RETURNS scalar_type AS BEGIN ... END

  2. < p>多语句表值:

    CREATE FUNCTION ... RETURNS @r TABLE(...) AS BEGIN ... END

  3. 内联表值:

    CREATE FUNCTION ... RETURNS TABLE AS RETURN SELECT ...

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

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

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


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

I realize this is a very old question, but I don't see one crucial aspect mentioned in any of the answers: inlining into query plan.

Functions can be...

  1. Scalar:

    CREATE FUNCTION ... RETURNS scalar_type AS BEGIN ... END

  2. Multi-statement table-valued:

    CREATE FUNCTION ... RETURNS @r TABLE(...) AS BEGIN ... END

  3. Inline table-valued:

    CREATE FUNCTION ... RETURNS TABLE AS RETURN SELECT ...

The third kind (inline table-valued) are treated by the query optimizer essentially as (parametrized) views, which means that referencing the function from your query is similar to copy-pasting the function's SQL body (without actually copy-pasting), leading to the following benefits:

  • The query planner can optimize the inline function's execution just as it would any other sub-query (e.g. eliminate unused columns, push predicates down, pick different JOIN strategies etc.).
  • Combining several inline function doesn't require materializing the result from the first one before feeding it to the next.

The above can lead to potentially significant performance savings, especially when combining multiple levels of functions.


NOTE: Looks like SQL Server 2019 will introduce some form of scalar function inlining as well.

小霸王臭丫头 2024-08-05 17:43:24
  • 函数必须返回值,但存储过程则不然。
  • Select 语句仅在 UDF 中接受,而 DML 语句不需要。
  • 存储过程接受任何语句以及 DML 语句。
  • UDF 只允许输入,不允许输出。
  • 存储过程允许输入和输出。
  • Catch 块不能在 UDF 中使用,但可以在存储过程中使用。
  • UDF 中的函数中不允许进行事务处理,但在存储过程中允许进行事务处理。
  • UDF 中只能使用表变量,而不能使用临时表。
  • 存储过程允许表变量和临时表。
  • UDF 不允许从函数调用存储过程,而存储过程允许调用函数。
  • UDF 用于 join 子句,而存储过程不能用于 join 子句。
  • 存储过程总是允许返回零。 相反,UDF 的值必须返回到预定点。
  • 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.
兲鉂ぱ嘚淚 2024-08-05 17:43:24
  • 函数可以在 select 语句中使用,而 as 过程不能使用。

  • 存储过程同时接受输入和输出参数,但函数仅接受输入参数。

  • 函数不能返回 text、ntext、image 和 type 类型的值。 程序可以的时间戳。

  • 函数可以在 create table 中用作用户定义的数据类型,但过程不能。

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

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

  • Functions can be used in a select statement where as procedures cannot.

  • Stored procedure takes both input and output parameters but Functions takes only input parameters.

  • Functions cannot return values of type text, ntext, image & timestamps where as procedures can.

  • Functions can be used as user defined datatypes in create table but procedures cannot.

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

Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get’s executed and the return
Type is returned as the result set.

望笑 2024-08-05 17:43:24

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

此外,如果将其放在 WHERE 子句中,SQL 引擎可能会生成错误的执行计划。

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

有关更多详细信息,请参阅 Joe Sack 的以下文章
https: //techcommunity.microsoft.com/t5/sql-server/introducing-interleaved-execution-for-multi-statement-table/ba-p/385417

Generally using stored procedures is better for perfomances.
For example in previous versions of SQL Server if you put the function in JOIN condition the cardinality estimate is 1 (before SQL 2012) and 100 (after SQL 2012 and before of SQL 2017) and the engine can generate a bad execution plan.

Also if you put it in WHERE clause the SQL Engine can generate a bad execution plan.

With SQL 2017 Microsoft introduced the feature called interleaved execution in order to produce a more accurate estimate but the stored procedure remains the best solution.

For more details look the following article of Joe Sack
https://techcommunity.microsoft.com/t5/sql-server/introducing-interleaved-execution-for-multi-statement-table/ba-p/385417

扮仙女 2024-08-05 17:43:24

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

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

  1. 系统定义

  2. 用户定义

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

  1. 系统存储过程
  2. 用户定义过程

In SQL Server, functions and stored procedure are two different types of entities.

Function: In SQL Server database, the functions are used to perform some actions and the action returns a result immediately.
Functions are two types:

  1. System defined

  2. User defined

Stored Procedures: In SQL Server, the stored procedures are stored in server and it can be return zero, single and multiple values.
Stored Procedures are two types:

  1. System Stored Procedures
  2. User Defined Procedures
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文