日期:2014-05-18  浏览次数:20471 次

求一个字符串字段,过滤后只保留数字的选择语句
有一个字段是字符串型的   例如:
  字段(nums)值:
'B20050702 '
'CD20070223 '
'28746594号 '
'P2874632 '

当我查找所要的记录时只能是输入数字   如 '20070518 ',没有 'B ', 'C ', 'P ', '号 '这些传过来,   如果用
  select   *   from   table1   where   nums   like   '%20070518% '
的话,select   *   from   table1   where   nums     like   '%8% '
这样结果都一样,不合要求,而用   ...Replace(Replace(nums, '非数字 ', ' '), '非数字 ', ' ')....= '20070518 '这种方法的效率太低了。
求救,有没有更好的方法!

------解决方案--------------------
如果只希望查找nums中只包含数字而不包含其它字符的记录,可以这样:
declare @t table(id int,nums varchar(20))
insert @t
select 1, 'B20050702 ' union all
select 2, 'CD20070223 ' union all
select 3, '28746594号 ' union all
select 4, 'P2874632 ' union all
select 5, 'T20070518日 ' union all
select 6, '20070518 ' /*这行记录只包含数字*/

declare @str varchar(10)
set @str = '20070518 '
select * from @t where patindex( '%[^0-9]% ',nums) = 0 and charindex(@str,nums) > 0

/*结果
id nums
-----------------
6 20070518
*/

------解决方案--------------------
借用楼上的数据

如果只是数字的话,用isnumeric判断旧可以了
declare @t table(id int,nums varchar(20))
insert @t
select 1, 'B20050702 ' union all
select 2, 'CD20070223 ' union all
select 3, '28746594号 ' union all
select 4, 'P2874632 ' union all
select 5, 'T20070518日 ' union all
select 6, '20070518 ' /*这行记录只包含数字*/

select * from @t where isnumeric(nums)=1

id nums
----------- --------------------
6 20070518