将varchar值转换为int,而不会在输入错误时抛出异常

Raj*_*Rao 21 sql-server

有没有办法调用Sql Server函数Convert/Cast而不让它们抛出异常?

基本上,我有一个包含字母数字数据的列,我从字段中提取值,我想将数据显示为整数值.有时提取的数据不是数字,在这种情况下我希望Sql Server跳过该行(返回null或0).

现在,Sql select语句失败,并且"将nvarchar值'xxxxx'转换为数据类型int时转换失败.

我想要的是类似于C#的int.TryParse.

建议?

Joe*_*lli 29

select case when isnumeric(YourColumn + '.0e0') = 1 
            then cast(YourColumn as int) 
            else NULL 
       end /* case */
    from YourTable
Run Code Online (Sandbox Code Playgroud)

  • 我认为在你的解决方案中解释魔术'.0e0'`是值得的:它确保该值是一个整数.`IsNumeric('1.5')`和`IsNumeric('1e5')`都返回true,但是无法转换为int.`IsNumeric('1.5.0e0')`和`IsNumeric('1e5.0e0')`都将返回false (4认同)

Dev*_*ner 11

在SQL Server 2012中有一些功能

try_cast
try_convert
try_parse