SQL中ISNULL的问题。

时间:2025-05-05 08:06:19

今天在写SQL代码的时候写了个 ISNULL(变量1,变量2),返回的结果居然是 "*" ,这个星号,郁闷了很久。

代码大意如下:

declare @str1 varchar(1)
declare @str2 int
set @str2=222
select ISNULL(@str1,@str2)

返回结果:" * ",这个郁闷啊。

修改下代码:

declare @str1 varchar(4)
declare @str2 int
set @str2=222
select ISNULL(@str1,@str2)

返回结果: " 222 " 。

再次修改代码:

declare @str1 varchar(4)
declare @str2 varchar(8)
set @str2=''
select ISNULL(@str1,@str2)

返回结果:"  2222 "。

经过这三次的试验结果:猜测isnull返回的结果类型,与第一个变量是息息相关的,甚至就取决于第一个变量的类型。

官方解释:

Syntax

 
ISNULL ( check_expression , replacement_value )

Arguments

check_expression

Is the expression to be checked for NULL. check_expression can be of any type.

replacement_value

Is the expression to be returned if check_expression is NULL. replacement_value must be of a type that is implicitly convertible to the type of check_expresssion.

Return Types

Returns the same type as check_expression.

Remarks

The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different.

返回值是第二个参数,会转成第一个参数的类型,转换失败,就会报异常或者出现前面的"*",星号。