Reputation: 50
Trying to understand the reason for the below behavior in SQL Server.
The below expression returns '*' on my server:
Select IsNull(NullIF(RTrim(NULL), ' '), '**')
Shouldn't it be returning '**'?
If I use any of the below statements instead, it correctly returns '**'.
sql_variant
variable for RTrim(NULL)
declare @a sql_variant = RTRIM(NULL)
Select IsNull(NullIF(@a, ' '), '**')
char(2)
variabledeclare @a char(2)
Set @a = NULL
Select IsNull(NullIF(RTrim(@a), ' '), '**')
SQL Version: SQL Server 2008 SP3 ANSI Settings: Default SSMS settings.
Upvotes: 0
Views: 499
Reputation: 7960
Because only the first character is returned at your query since there is no initial data type for the parameter null
. Try:
Select IsNull(NullIF(RTrim(cast(NULL as varchar(max))), ' '), '**')
Select IsNull(NullIF(RTrim(cast(NULL as varchar(max))), ' '), '*****')
Upvotes: 1
Reputation: 95564
The reason is because your NULL
has no initial data type, thus, when SQL Server converts it to a varchar
, it effectively converts it into varchar(1)
. Hence the value returned is only '*'
.
To get the expected behaviour you need to let SQL Server know what the data type of the NULL
is. For example, by declaring a variable (as you did) or use CAST
or CONVERT
:
DECLARE @String varchar(2) = NULL;
SELECT ISNULL(NULLIF(RTRIM(@String), ' '), '**');
SELECT ISNULL(NULLIF(RTRIM(CONVERT(varchar(2),NULL)), ' '), '**');
Upvotes: 2