简体   繁体   English

SQL Server 2014中的ISNULL()函数表现异常

[英]ISNULL() function in SQL Server 2014 behaving unexpectedly

Declare @Var1 Varchar(5) = Null
Declare @Var2 Varchar(10) = 'ABCDEFGHIJ'

SELECT ISNULL(@Var1, @Var2) AS Result

I excepted the result to be ' ABCDEFGHIJ' , but the result is 'ABCDE' . 我将结果排除为“ ABCDEFGHIJ' ,但结果为'ABCDE'

Is this the normal behavior of the function or I am missing anything? 这是该函数的正常行为还是我遗漏了什么?

You have used varchar(5) that's why this is happening 您使用了varchar(5),这就是为什么这样

use below 在下面使用

 Declare @Var1 Varchar(50) = Null

this will give your expected answer 这将给您预期的答案

You should use coalesce function because the Coalesce() function returns the first non-null value among its arguments. 您应该使用coalesce因为函数Coalesce()函数返回它的参数中的第一个非空值。

SELECT COALESCE(@Var1, @Var2) AS Result

Or you can change size of your declared variable. 或者,您可以更改声明的变量的大小。 Both will give you expected output. 两者都会给您预期的输出。

To answer your question, yes this is the normal behavior of ISNULL . 要回答您的问题,是的,这是ISNULL的正常行为。 it takes the type of the first expression. 它采用第一个表达式的类型。

reference here https://msdn.microsoft.com/en-us/library/ms184325.aspx 在这里参考https://msdn.microsoft.com/en-us/library/ms184325.aspx

The value of check_expression is returned if it is not NULL; 如果check_expression不为NULL,则返回该值;否则返回false。 otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different. 否则,如果类型不同,则将replace_value隐式转换为check_expression类型后返回。 replacement_value can be truncated if replacement_value is longer than check_expression. 如果replacement_value的长度大于check_expression,则replacement_value可以被截断。

As an alternative you should rather use COALESCE 作为替代,您应该使用COALESCE

使用COALESCE函数:不确定为什么ISNULL返回这样的输出,但是假设在检查ISNULL(p1,p2) ,它将仅考虑第一个参数的大小。

SELECT COALESCE(@Var1, @Var2) AS Result

That is because your source variable is of length 5 so it has truncated the other part 那是因为您的源变量的长度为5,所以它已经截断了另一部分

Declare @Var1 Varchar(10) = Null
Declare @Var2 Varchar(10) = 'ABCDEFGHIJ'

SELECT ISNULL(@Var1, @Var2) AS Result

ISNULL(@Var1, @Var2)语句将拷贝的价值@Var2@var1如果@var1是空的,长度@var15 ,这就是为什么它是只显示前五个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM