有谁知道如何把这个字符串: "Smith, John R"
变成这个字符串: "jsmith" ?
我需要使用 lower() 将所有内容小写
查找逗号的位置并跟踪它的整数位置值
获取该逗号之后的第一个字符并将其放在字符串前面
然后获取整个姓氏并将其粘贴在第一个首字母之后。
旁注 - instr() 函数与我的版本不兼容
感谢您的帮助!
首先编写您自己的 INSTR 函数 - 例如将其称为 my_instr。它将从字符 1 开始并循环,直到找到一个“,”。
然后像 INSTR 一样使用。
最好的方法是使用 Oracle 正则表达式功能,如下所示:
SELECT LOWER(regexp_replace('Smith, John R',
'(.+)(, )([A-Z])(.+)',
'\3\1', 1, 1))
FROM DUAL;
也就是说,1)当您找到任何一组字符的模式时,后跟“,”,后跟一个大写字符,然后是任何剩余的字符,取第三个元素(名字的首字母)并附加姓氏。然后将所有内容变为小写。
您的旁注:“instr() 函数与我的版本不兼容”对我来说没有意义,因为该函数已经存在了很长时间。检查您的版本,因为正则表达式仅在 9i 版中添加到 Oracle。
感谢您的积分。
- 炖
instr() 与您的版本不兼容?甲骨文?您使用的是版本 4 还是什么?
我很难相信您无法访问正确的 instr() 但如果是这种情况,请实现您自己的版本。
假设你已经理顺了:
选择 substr( 低('史密斯,约翰 R') , instr('Smith, John R', ',') + 2 , 1 ) || -- first_initial substr( 低('史密斯,约翰 R') , 1 , instr('史密斯, 约翰 R', ',' ) - 1 ) - 姓 从双;
此外,请注意您假设所有名称都将采用该格式。注意逗号后的单个空格以外的其他内容,姓氏中包含“Parisi, Jr.”等数据。
没有必要创建自己的函数,坦率地说,如果可以使用已经存在的 sql 函数相当容易地完成,这似乎是浪费时间。必须注意草率的数据输入。
这是实现既定目标的另一种方法:
with name_list as
(select ' Parisi, Kenneth R' name from dual)
select name
-- There may be a space after the comma. This will strip an arbitrary
-- amount of whitespace from the first name, so we can easily extract
-- the first initial.
, substr(trim(substr(name, instr(name, ',') + 1)), 1, 1) AS first_init
-- a simple substring function, from the first character until the
-- last character before the comma.
, substr(trim(name), 1, instr(trim(name), ',') - 1) AS last_name
-- put together what we have done above to create the output field
, lower(substr(trim(substr(name, instr(name, ',') + 1)), 1, 1)) ||
lower(substr(trim(name), 1, instr(trim(name), ',') - 1)) AS init_plus_last
from name_list;
HTH,加布