字符集为西欧字符集Oracle截取字符串
作者:olivenan
由于Oracle系统采用的是西欧字符集WE8ISO8859P1,所以导致在截取字母和汉字组合的字符串时经常会产生乱码,这是由于截取了半个汉字所致。
经过试验找到其截取方法:
1、首先建立一个保存ascii值从32到126的字符
-- Create table
create table ENGLISHWORDS
(
WORDS VARCHAR2(2),
ASCILLVALUE NUMBER(3)
)
2、编写函数
i_title为输入的字符串,i_len 截取长度为偶数
create or replace function substringtitle(i_title in varchar2,i_len in number)
return varchar2 is
-- Result varchar2(200);
i int := 0;
v_title varchar2(200);
v_word varchar2(10);
v_number int;
begin
select substr(i_title, 1, i_len) into v_title from dual;
--select length('strtest')-length(replace('strtest','t')) from dual;
--每次截取一个字符然后查找其在表englishwords 是否存在,如果存在i加1
--注:虽然在截取过程中会出现截取半个汉字的情况,考虑到englishwords表中只存在英文字符,所以此时也不会找到对应的项
for b in 1 .. i_len loop
v_word := substr(v_title, b, 1);
begin
select 1 into v_number from englishwords t where t.words = v_word;
i := i + 1;
exception
when no_data_found then
null;
end;
end loop;
/* for a in (select words from englishwords) loop
v_word:=a.words;
if (instr(v_title, v_word) > 0) then
i := i + 1;
end if;
end loop;*/
--查看英文字符出现的次数,如果是奇数,上面的截取结果就出现了乱码,所以需要将最后半个字符舍去
if (mod(i, 2) = 1) then
v_title := substr(v_title, 1, i_len-1);
end if;
--result := v_title;
null;
return(v_title);
end;
如果大家有什么好的方法,欢迎提出,谢谢。