oracle中to_char函数转换后多出空格的问题

    今天编写往数据库中插入200万数据的存储过程,遇到to_char的问题,记录下来与大家分享。
    主键id为32位varchar类型,由数字组成,高位用0补足,例如'00000000000000000000000000000001'。
    存储过程如下:
create or replace procedure insertintouserstmp20151104(numb in number) as
user_id varchar2(32);
i number := 1;
begin
  for i in 1..numb loop
    user_id := to_char(UCMP_INSERTUSER.Nextval,'00000000000000000000000000000000');--UCMP_INSERTUSER为自增序列
    insert into users_tmp20151104(user_id,password,status,type_code,cust_type,register_source,create_tm,mem_no,nick_name,account_status)
values(user_id,'af8f9dffa5d420fbc249141645b962ee','Y','0','0','1',sysdate,user_id,user_id,'1');
    if(mod(i,1000)=0) then
        commit;
    end if;
  end loop;
  commit;
end insertintouserstmp20151104;

    调用存储过程时提示user_id长度为32位,实际为33位,测试发现是to_char指定了转换格式参数后,长度比预想的32位多了一位
   select length(to_char(11)) from dual;--2
   select length(to_char(11,'00')) from dual;--3
   网上查询资料发现,to_char转换指定格式时,字符串前面增加了一个空格,所以长度比指定格式长度增加了1,网上流传原因是:那个空格位置是放符号的,正的数字就空了,负的就是一个‘-’号而没有空格。
   select length(to_char(1,'00')) from dual;-- 3
   select length(to_char(-1,'00')) from dual;-- 3
  
   解决方法:用trim转换或者fm
   select length(trim(to_char(1,'00'))) from dual;-- 2
   select length(to_char(1,'fm00')) from dual;-- 2

再执行存储过程,运行成功,ok!



猜你喜欢

转载自lucizhang.iteye.com/blog/2254927