Search code examples
sql-servercharindex

SQL charindex returns 0


I am confused in using charindex operator in SQL server. When I concatenate the car field with commas I get the desired output but when I check again the index of 12 in the result, I get 0 . The field car is INT and I have also checked the 12 without single quotation.

select concat(',',car,',') as car from drivers where id=38

output: ,12,

select CHARINDEX(concat(',',car,','),'12') as carindex from drivers where id=38

output: 0


Solution

  • You should put an expression to find at the first place:

    select CHARINDEX('12', CONCAT(',', @car,','), 0)
    

    As MSDN says:

    CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )