Question

I am developing a web application using JSP + Servlets and Oracle10 as back-end.

I have a table for storing information related to Customers:

|ID        |Name            |City          |
|N0001     |ABC             |NASIK         |
|N0002     |PQR             |NASIK         |
|N....     |...             |NASIK         |
|N9999     |XYZ             |NASIK         |
|N10000    |LMN             |NASIK         |
|N10001    |MNO             |NASIK         |

In above table ID is a primary key, which is auto-generated depending upon the City (first Character of City + Number(Number must be minimum 4 character long, so for first ID, three leading zeroes will be added to number))

For Generating ID:
I am using following query for getting Largest ID from table, and then some java code Auto Generate Next ID.

query = "select ID from CUST where CITY='NASIK' order by ID desc";

Then getting the first ID from ResultSet which is as expected till the ID reach to the N9999, but when ID is N10000 or above then query is giving me N9999 as Largest ID.

Output after N9999:

ID
----------
N9999
N10001
N10000
N0002
N0001

Output Expecting

ID
----------
N10001
N10000
N9999
N0002
N0001

So my question is that is there anything wrong in above query? Or is there any better way to Auto Generate ID which contains String.

Edit1 My requirement is to auto generate ID which will contain character at starting position.

Was it helpful?

Solution

use this query

select ID from CUST where CITY='NASIK' order by to_number(substr(ID,2)) desc;

OTHER TIPS

Since ID is a String not a number, it is sorted differently. it would sort as you wish if you had done sth like:

0001N
0002N
...

or stored only numbers, not Strings

With the INSERT, without inserting the prinary key ID, you can get the "generated keys."

String sql = "INSERT INTO Customers(Name, City) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql,
     PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, ...);
stmt.setString(2, ...);
int affectedRows = stmt.executeUpdate();

// Get the ID:
String pk = "";
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next()) {
    pk = keys.getString(1);
}

It is so ugly, loop x loop, as one could have inserted more than one row, and the generated keys per row could be more than one.

As you can see, this is prove against concurrent parallel INSERTS.

About the sorting problem: you might go for a purely numerical ID, maybe a composed primary key CHAR(1), INT.

quick fix would be to increase the number of leading '0' after the character. But then the problem will occur later (e.g. 99999 and 100000).

Hence i would suggest to interpret the ID as a number from the second character on and do the order comparison upon that number value.

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