Search code examples
sqlsql-server-2005

SQL for nvarchar 0 = '' & = 0?


I was searching for integers in a nvarchar column. I noticed that if the row contains '' or 0 it is picked up if I search using just 0.

I'm assuming there is some implicit conversion happening which is saying that 0 is equal to ''. Why does it assign two values?

Here is a test:

--0 Test
create table #0Test (Test nvarchar(20))

GO
insert INTO #0Test (Test)
    SELECT ''
UNION ALL
    SELECT 0
UNION ALL
    SELECT ''

Select *
from #0Test

Select *
from #0Test
Where test = 0

SELECT *
from #0Test
Where test = '0'

SELECT *
from #0Test
Where test = ''

drop table #0Test 

Solution

  • The behavior you see is the one describe din the product documentation. The rules of Data Type Precedence specify that int has higher precedence than nvarchar therefore the operation has to occur as an int type:

    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

    Therefore your query is actually as follow:

    Select *
    from #0Test
    Where cast(test as int) = 0;
    

    and the empty string N'' yields the value 0 when cast to int:

    select cast(N'' as int)
    
    -----------
    0
    
    (1 row(s) affected)
    

    Therefore the expected result is the one you see, the rows with an empty string qualify for the predicate test = 0. Further proof that you should never mix types freely. For a more detailed discussion of the topic, see How Data Access Code Affects Database Performance.