SQLServer:为什么要避免使用表值用户定义函数?

2021-09-15 00:00:00 user-defined-functions sql-server

我有一个相当大的查询,需要在几个存储过程中使用,我想将其转换为 UDF 以使其更易于维护(视图不起作用,这需要一堆参数),但是我曾经与之交谈过的每个人都告诉我 UDF 的速度非常慢.

I have a rather huge query that is needed in several stored procedures, and I'd like to shift it into a UDF to make it easier to maintain (A view won't work, this takes in a bunch of parameters), however everyone I've ever talked to has told me that UDF's are incredibly slow.

虽然我不知道究竟是什么让它们变慢,但我会猜测它们是,但看到我没有在连接中使用这个 UDF,而是返回一个表变量,我认为它不会那么糟糕.

While I don't know what exactly makes them slow, I'm will to guess that they are, but seeing as I'm not using this UDF within a join, but instead to return a table variable, I think it wouldn't be that bad.

所以我想问题是,我应该不惜一切代价避免使用 UDF 吗?任何人都可以指出具体的证据表明它们更慢吗?

So I guess the question is, should I avoid UDFs at all cost? Can anyone point to concrete evidence stating that they are slower?

推荐答案

标量 UDF 非常慢,内联 UDF 实际上是宏,因此它们非常快:几篇文章:

Scalar UDFs are very slow, inline UDFs are in fact macros, as such they are very fast: A few articles:

使用表值 UDF 重用您的代码

许多嵌套的内联 UDF 非常快

有关标量 UDF 缓慢的更多链接:

More links on slowness of scalar UDFs:

带有日期时间的 UDF 的 SQL Server 性能模式参数

并非所有 UDF 都对性能不利

相关文章