筛选某CHAR型字段中纯数字值的数据
地址:http://www.wlive.net/archives/10
前几天,一朋友问了这样一个问题,他有张表,有个字段,是char型的,但是,里面的值,有的是纯数字,有的是数字与字母混合,现在有个需求,要求把纯数字的的那些行提取出来,问我该怎么办,我一时也没什么太好的办法,今天,在lazy dba上看到一个类似的需求,以及一个类似的解决方案,看起来能够满足要求,测试了一下,looks good 呵呵.
做法其实很简单,用到了一个translate函数,该函数的语法和用法解释如下:
SYNTAX:
TRANSLATE(char,from,to)
PURPOSE:
Returns char with all occurrences of each character in from replaced
by its corresponding character in to. Characters in char that are
not in from are not replaced. The argument from can contain more
characters than to. In this case, the extra characters at the end
of from have no corresponding characters in to. If these extra
characters appear in char, they are removed from the return value.
You cannot use empty string for to in order to remove all characters
in from the return value. Oracle interprets the empty string
as null, and if this function has a null argument, it returns null.
解释起来就是说用户可以指定替换规则,根据指定的替换规则,把原字段里面的值替换了,例如:

类似于replace的作用,但又有增强,如果没有定义,那就为空,如:

这里,sdf在”from”格式里,但没有在”to”的格式里,所以就被转换为空,正是由于他有这个特性,才被我们拿来作为判断一个字段是否为纯数字使用.思路是这样的,我们定义一个转换规则,从’abcdefghijklmnopqrstuvwxyz0123456789′转换到’abcdefghijklmnopqrstuvwxyz’,如果字段是纯数字,经过转换,应该返回空值,如果字段包含有字母,则应该返回有具体的字母值,这时候,再用decode进行判断是否为空,就能够判断出是否是纯数字的值了:

再进一步研究,发现,其实我们要做的事,只是想把数字转换为空,其余不管,所以,规则根本不用如此复杂,只要定义从’a1234567890′到’a'的一个转换,就可以实现包含任意字符的字段了:

由此,该问题得以解决.经过测试通过.
--EOF--

0 Responses to “筛选某CHAR型字段中纯数字值的数据”