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
The behavior you see is the one describe din the product documentation. The rules of Data Type Precedence specify that
inthas higher precedence thannvarchartherefore the operation has to occur as aninttype:Therefore your query is actually as follow:
and the empty string
N''yields the value 0 when cast toint: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.