The value is returned instead of NULL when using function with OUTER APPLY(将函数与 OUTER APPLY 一起使用时,将返回该值而不是 NULL)
问题描述
我在使用内联函数时得到奇怪的结果.代码如下:
I am getting strange results when using inline function. Here is the code:
IF EXISTS (
SELECT * FROM sys.objects AS o WHERE name = 'vendor_relation_users'
) DROP FUNCTION dbo.vendor_relation_users;
GO
CREATE FUNCTION [dbo].[vendor_relation_users]
(
@user_name CHAR(12)
)
RETURNS TABLE
AS
RETURN (SELECT @user_name AS user_name WHERE @user_name NOT LIKE '06%');
GO
DECLARE @u CHAR(12) = '066BDLER'
SELECT a.user_name, is_v.user_name
FROM (SELECT @u AS user_name) a
OUTER APPLY [dbo].[vendor_relation_users](@u) AS is_v
SELECT a.user_name, is_v.user_name
FROM (SELECT @u AS user_name) a
OUTER APPLY (SELECT @u AS user_name WHERE @u NOT LIKE '06%') AS is_v
SELECT * FROM [dbo].[vendor_relation_users](@u)
所以在第一个 SELECT 语句中,我只是对函数进行了 OUTER APPLied 并返回结果.
So in the first SELECT statement I've just OUTER APPLied the function and it returns the result.
在下一个语句中,我从函数中取出代码并将其直接放入 OUTER APPLY 语句中.
In the next statement I've took the code from function and put it straight to the OUTER APPLY statement.
最后一个语句只是直接的函数调用.
And the last statement is just the direct function call.
我不明白为什么 FIRST 查询会返回值...
推荐答案
这是一个非常有趣的查询.第一个查询的行为取决于您是否使用 OPTION (RECOMPILE)
.
This is a very interesting query. The behaviour of your first query depends upon whether you use OPTION (RECOMPILE)
or not.
正如您指出的那样:
DECLARE @u CHAR(12) = '066BDLER'
SELECT a.user_name, is_v.user_name
FROM (SELECT @u AS user_name) a
OUTER APPLY [dbo].[vendor_relation_users](@u) AS is_v
返回:
user_name user_name
066BDLER 066BDLER
但是如果你像这样添加OPTION (RECOMPILE)
:
but if you add OPTION (RECOMPILE)
like this:
SELECT a.user_name, is_v.user_name
FROM (SELECT @u AS user_name) a
OUTER APPLY [dbo].[vendor_relation_users](@u) AS is_v
OPTION (RECOMPILE)
你正确理解:
user_name user_name
066BDLER NULL
我怀疑这是由于查询优化器如何根据基数估计使这些内联函数短路的错误.如果您查看这两个查询的查询计划,您会发现没有 OPTION RECOMPILE 的那个只返回一个常量.
I suspect this is due to a bug in how the query optimiser short circuits these inline functions due to cardinality estimates. If you look at the query plan for the two queries you will see that the one without the OPTION RECOMPILE just returns a constant.
这篇关于将函数与 OUTER APPLY 一起使用时,将返回该值而不是 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将函数与 OUTER APPLY 一起使用时,将返回该值而不


基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01