如何将 nvarchar 转换为 int

how to Convert nvarchar to int

我需要根据包含数字的 nvarchar 列获取数据,但出现此错误: 将 nvarchar 值“362X”转换为数据类型 int 时转换失败。 我试过这个:

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

我错过了什么?

在SQL服务器中,可以使用try_convert()try_cast():

where try_cast(modelcode as int) > 10000

在其他数据库中,您可以使用 case 或正则表达式:

where (case when modelcode ~ '^[0-9]+$' then cast(modelcode as int) end) > 10000

将除负号以外的所有非数字字符替换为null,然后转换为INT。

select  modelcode from model where  cast(REGEXP_REPLACE(modelcode,'^0-9-','') as int )> 10000