2015-07-03 26 views
0

我有一个包含以下字符串的数据:选择包含数字仅排

Hello | World | 40 
Hi | World | 24244 
One | Two | 27 
This | That | 84f 
Yes | No | 456gf 
The | Test|54 

现在我需要编写查询只让那些行,其中到底唯一号码,过滤那些在他们身后的字符。以上设置的结果:

Hello | World | 40 
Hi | World | 24244 
One | Two | 27 
The | Test|54 

我尝试了几种使用通配符的方法,但没有成功。

TB LIKE '%_|_[0-9]%' OR TB LIKE '%_|[0-9]%' 
AND TB NOT LIKE '%[0-9][^a-z]%' 

等等。显然,例如此查询还返回包含456gf和84f的行。

+0

如果你只是想以确保最后一个字符是数字,而不是一个字母,那么你可以使用'ISNUMERIC(右(字符串,1))= 1'或者你可以测试整个在最后一个管道之后的子串。请注意,对于某些符号,isnumeric也会返回true(例如,+ - $) – jpw

+1

@jpw - OP甚至可以使用TB LIKE'%[0-9]'作为检查字符串最后一个字符的方式一个没有'isnumeric'的问号的int – ughai

+0

@ughai啊,对。那会更好。 – jpw

回答

0

我觉得你快到了。 我不确定你的意思是_或空间在你的模式。 我认为主要的问题是“NOT ^”技巧没有按预期工作。你真的只希望它适用于最后一节。

试试这个作为你的WHERE ...

LTRIM(REVERSE(SUBSTRING(REVERSE(TB),1,CHARINDEX('|',REVERSE(TB)) - 1))) NOT LIKE '%[^0-9]%' 
0

与CTE尝试,

declare @t table (field1 varchar(20),field2 varchar(20),field3 varchar(20)) 
insert into @t 
     (field1, field2, field3) 
values ('Hello','World','40') 
     ,('Hi', 'World','24244') 
     ,('One','Two','27') 
     ,('This', 'That','84f') 
     ,('Yes','No','456gf') 
     ,('The','Test','54') 
;with cte as(
select *, CASE ISNUMERIC(field3) WHEN 1 THEN CAST(field3 AS int) ELSE null end as Field4 
from @t) 
SELECT cte.field1,cte.field2,cte.field3 FROM cte 
where field4 is not null 
0

使用try_parse insted的的ISNUMERIC,因为它比ISNUMERIC更快。

declare @t table (field1 varchar(20),field2 varchar(20),TB varchar(20)) 
insert into @t 
     (field1, field2, TB) 
values ('Hello','World','40') 
     ,('Hi', 'World','24244') 
     ,('One','Two','27') 
     ,('This', 'That','84f') 
     ,('Yes','No','456gf') 
     ,('The','Test','54') 
; 
Select * from @t 
WHERE TRY_PARSE(Tb as int) IS NOT NULL 
0

这应该满足您的要求(该表称为吨,列C):

select * from t where isnumeric(substring(c, charindex('|', c, charindex('|', c, 0) + 1) + 1, len(c))) = 1 

内CHARINDEX charindex('|', c, 0)找到的第一个管道符号的位置时,外部人们发现的位置第二,因为它开始后面的第一个搜索。之后,isnumeric检查余数是否确实是一个数字。测试:

declare @t table(c varchar(100)) 
insert into @t (c) values 
(' Hello | World | 40'), 
('Hi | World | 24244'), 
('One | Two | 27 '), 
('This | That | 84f '), 
('Yes | No | 456gf '), 
('The | Test|54  ') 

select charindex('|', c, charindex('|', c, 0) + 1), charindex('|', c, 0) from @t 
select * from @t where isnumeric(substring(c, charindex('|', c, charindex('|', c, 0) + 1) + 1, len(c))) = 1 
相关问题