Skip to content
Advertisement

how to Convert nvarchar to int

I need to get data according to nvarchar coloumn that holds numbers,I get this error: Conversion failed when converting the nvarchar value ‘362X’ to data type int. I tried this:

select  modelcode from model 
where  cast(modelcode as int )> 10000 - ERROR
where  cast(modelcode as bigint )> 10000 - ERROR
where  pws_modelcode+0 > 10000 - ERROR
order by ModelCode asc

What am I missing ?

Advertisement

Answer

In SQL Server, you can use try_convert() or try_cast():

where try_cast(modelcode as int) > 10000

In other databases, you can use a case perhaps with regular expressions:

where (case when modelcode ~ '^[0-9]+$' then cast(modelcode as int) end) > 10000
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement