如何快速比较许多字符串?

时间:2012-08-07 18:16:25

标签: sql sql-server regex database tsql

在SQL Server中,我有一个包含数字的字符串列。我需要的每个条目只有一个数字,因此不需要解析。我需要一些方法来查找包含从400到450的数字的所有行。而不是:

...where my stringcolumn like '%400%' or stringcolumn like '%401%' or stringcolumn like '%402%' or ...

有没有更好的可以节省一些打字?

这些行中还有其他值,例如:'5335154',test4559 @ me.com','555-555-5555'。需要考虑过滤掉那些。

4 个答案:

答案 0 :(得分:3)

...where stringcolumn like '4[0-4][0-9]' OR stringcolumn = '450'

如果要限制为3位,则不需要通配符。

答案 1 :(得分:2)

使用正则表达式完成此任务。

...where stringcolumn like '4[0-4][0-9]' OR stringcolumn like '450'

答案 2 :(得分:0)

单程

WHERE Column like '%4[0-4][09]%'
OR Column LIKE '%500%'

请记住,这会选择带有数字的任何内容,因此也会返回5000

答案 3 :(得分:0)

我会做以下事情:

select t.*
from (select t.*,
             (case when charindex('4', col) > 0
                   then substrint(col, charindex('4', col), charindex('4', col) + 2)
              end) as col4xx
      from t
     ) t
where (case when isnumeric(col4xx) = 1
            then (case when cast(col4xx as int) between 400 and 450 then 'true'
                  end)
       end) = 'true'

我不喜欢在WHERE子句中使用case语句。但是,为了确保转换为数字,需要这样做(或者转换可能成为另一个子查询中的列)。请注意,以下内容不相同:

where col4xx between '400' and '450'

由于字符串'44A'匹配。

相关问题