Question

I need to generate a unique serial number in our web application.

I have created a table called SerialNumber which will have only one row. In the begining it will have value like '0000000000' ten times zero. This will be incremented by one every time a serial number needs to be generated.

e.g. 0000000001, 0000000002 and so on.

I have kept the column datatype as Integer which stores values as 0, 1, 2 etc and not as 0000000001. I want the serial number to be ten digits only with zeros appended at the begining.

Please help me to write the stored proc for this.

Was it helpful?

Solution

select to_char(<column-value>, 'FM0000000000') from serialNumber;

I don't know what's behind your requirement, but most probably, you are better served with a sequence. Using a table to generate unique ids is usually a poor choice that should be reviewed.

As for a stored procedure along with a sequence, a basic frame to build upon could be:

The sequence:

create sequence serial_number_seq;

The stored procedure (actually: a function)

create or replace function next_serial_number return varchar2 as

       serial_number_ number;
       MAX_SR_NO number;
begin

       select serial_number_seq.nextval into serial_number_ from DUAL;

       Select MAX(sr_no) INTO MAX_SR_NO from serialNumber;

       serial_number_ := GREATEST(serial_number_, MAX_SR_NO); 

       return to_char(serial_number_, 'FM0000000000');

end    next_serial_number;
/

testing

begin
  dbms_output.put_line(next_serial_number);
  dbms_output.put_line(next_serial_number);
  dbms_output.put_line(next_serial_number);
  dbms_output.put_line(next_serial_number);
  dbms_output.put_line(next_serial_number);
  dbms_output.put_line(next_serial_number);
-- in the place where you use the serial number the greatest 
--  of inserted value from external system or sequence value will be used
 final_value:= next_serial_number;
end;
/

OTHER TIPS

Please use

lpad(serial_no, 10, '0');

more information at

http://www.techonthenet.com/oracle/functions/lpad.php

and it is also better to use sequence in oracle other than storing in table

http://www.techonthenet.com/oracle/sequences.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top