在使用 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
有更多 Precedence
在 char
, ''
将转换为 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
但在第二种情况下为
@charType
是 null
, ISNULL
将转换值 0
至 nvarchar
然后查询变成所以
PRINT CASE WHEN '0' = '' THEN 'true' ELSE 'false' END
因此它打印
false
关于sql-server - SQL 中的 ISNULL 和隐式数据类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632414/