简体   繁体   中英

PL/SQL character variable

All Items in my table are 7 digits. If I input something with 6 digits should show 0 at the beginning. (output should be 7 digits.)

For example:

Input= 123456 Output= 0123456

How can I write it in Oracle SQL?

I've tried that. But it does not work.

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;

does anyone have an idea?

Use TO_CHAR , with the leading 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

How about the lpad function?

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

Be careful though when the string is shorther than the length you want to fix.

Take a look at this example. http://sqlfiddle.com/#!4/3ae17/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM