sql-server - SQL 中的 ISNULL 和隐式数据类型转换

标签 sql-server tsql type-conversion isnull

在使用 ISNULL 时,我遇到了一个有点奇怪的数据类型转换行为。看这个:

PRINT CASE WHEN ISNULL('', 0) = 0 THEN 'true' ELSE 'false' END
PRINT CASE WHEN ISNULL('', 0) = '' THEN 'true' ELSE 'false' END
PRINT CASE WHEN ISNULL(NULL, 0) = '' THEN 'true' ELSE 'false' END

所有这些表达式的计算结果都为真。
但是当我声明一个 nvarchar 变量并将其设置为 NULL 时,会发生以下情况:
DECLARE @charType nvarchar; SET @charType = NULL;
PRINT CASE WHEN ISNULL(@charType, 0) = '' THEN 'true' ELSE 'false' END

这也应该评估为真,但它评估为假。为什么?

最佳答案

这里ISNULL('', 0)返回 ''ISNULL(NULL, 0)返回 0
Data Type Precedence ...

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned.



int有更多 Precedencechar , ''将转换为 int .
select cast('' as int) ==> 0

因此,在第一种情况下,所有 ''将转换为 0 ,所以查询将减少到
PRINT CASE WHEN 0 = 0 THEN 'true' ELSE 'false' END
PRINT CASE WHEN '' = '' THEN 'true' ELSE 'false' END
PRINT CASE WHEN 0 = 0 THEN 'true' ELSE 'false' END

因此它打印 true
ISNULL ...

Returns the same type as check_expression. If a literal NULL is provided as check_expression, returns the datatype of the replacement_value. If a literal NULL is provided as check_expression and no replacement_value is provided, returns an int



但在第二种情况下为 @charTypenull , ISNULL将转换值 0nvarchar然后查询变成

所以
PRINT CASE WHEN '0' = '' THEN 'true' ELSE 'false' END

因此它打印 false

关于sql-server - SQL 中的 ISNULL 和隐式数据类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632414/

相关文章:

带有特殊字符的 SQL LIKE

c# - SMO 代码支持 sql 2005 和 sql 2008

SQL 服务器 : Update table based on JSON

sql - 仅反转sql server中字符串的数字部分

c++ - 如何在 Arduino 中将 char 转换为 int

mysql - 如何在 sp_executesql 中使用来自其他存储过程的输入参数

sql - 将 XML 插入 SQL Server 表

sql - 当我们在 SQL Server 中对文本列进行透视时,为什么要使用 Max 函数?

c++ - 在 C++ 中对对象进行类型转换(请解释输出)

c++ - bool 数组在衰减方面的处理方式不同吗?