PL / SQL字符变量

时间:2013-09-05 13:17:20

标签: sql oracle plsql

我表中的所有项目都是7位数。如果我输入6位数的东西,应该在开头显示0。 (输出应为7位数。)

例如:

输入= 123456 输出= 0123456

如何在Oracle SQL中编写它?

我试过了。但它不起作用。

cursor c1 is
into art_no_tmp1
select  art_no
from    barticles b
where   b.ean_no_1 = '789546584587';

cursor checklength is
into len_number
select length(art_no_tmp1)
from    dual;


if(len_number = 6) then
      return '0'+art_no_tmp1;
else
      return art_no_tmp1;
end if;

有没有人有想法?

2 个答案:

答案 0 :(得分:5)

使用TO_CHAR与前导0 format

SQL> WITH DATA AS (
  2     SELECT 1       num FROM DUAL UNION ALL
  3     SELECT 12      num FROM DUAL UNION ALL
  4     SELECT 123     num FROM DUAL UNION ALL
  5     SELECT 1234    num FROM DUAL UNION ALL
  6     SELECT 12345   num FROM DUAL UNION ALL
  7     SELECT 123456  num FROM DUAL UNION ALL
  8     SELECT 1234567 num FROM DUAL
  9  )
 10  SELECT num, to_char(num, '0000000') FROM data;

       NUM TO_CHAR(NUM,'0000000')
---------- ----------------------
         1  0000001
        12  0000012
       123  0000123
      1234  0001234
     12345  0012345
    123456  0123456
   1234567  1234567

答案 1 :(得分:3)

lpad功能怎么样?

LPAD('123', 7, '0') = '0000123'

当字符串短于你想要修复的长度时要小心。

看看这个例子。 http://sqlfiddle.com/#!4/3ae17/2