T-SQL, string comparison with leading digit using parameters returns a false positive

sql, sql-server, t-sql

Solution

The default length for `NVARCHAR` is 1. Your three parameters effectively all contain just one single character.

If you change your declarations to

DECLARE @RandomParam1 NVARCHAR(32)
DECLARE @RandomParam2 NVARCHAR(32)
DECLARE @RandomParam3 NVARCHAR(32)

you will get the behavior you were expecting.

nchar and nvarchar

When n is not specified in a data definition or variable declaration statement, the default length is 1.

Problem

I was wondering if someone can explain this behaviour? ``` DECLARE @RandomParam1 NVARCHAR DECLARE @RandomParam2 NVARCHAR DECLARE @RandomParam3 NVARCHAR SET @RandomParam1 = '0HelloWorld' SET @RandomParam2 = '9HelloWorld' SET @RandomParam3 = '15HelloWorld' select 1 where '0' = @RandomParam1 -- true select 1 where '0' = '0HelloWorld' -- false select 1 where '9' = @RandomParam2 -- true select 1 where '15' = @RandomParam3 -- false ``` Why does a string comparison with parameters yield a different result than without parameters? And why does it claim that '0' = '0whatever'? I get that it may be that the parameter tries to compare it as numbers, but then the last example should be true aswell. Any ideas?

Original source