开发者

Generate encoding String according to creation order

开发者 https://www.devze.com 2022-12-30 05:07 出处:网络
I need to generate encoding String for each item I inserted into the database. for example: x00001 开发者_开发知识库for the first item

I need to generate encoding String for each item I inserted into the database. for example:

x00001 开发者_开发知识库for the first item
x00002 for the sencond item
x00003 for the third item

The way I chose to do this is counting the rows. Before I insert the third item, I count against the database, I know there're already 2 rows, so the next encoding is ended with 3. But there is a problem. If I delete the second item, the forth item will not be the x00004,but x00003.

I can add additional columns to table, to store the next encoding, I don't know if there's other better solutions ?


Most databases support some sort of auto incrementing identity field. This field is normally also setup to be unique, so duplicate ids do not occur.

Consult your database documentation to see how it is done in your database and use that - don't reinvent the wheel when you have a good mechanism in place already.


What you want is SELECT MAX(id) or SELECT MAX(some_function(id)) inside the transaction.

As suggested in Oded's answer a lot of databases have their own methods of providing sequences which are more efficient and depending on the DBMS might support non numeric ids.

Also you could have id broken down into Y and 00001 as separate columns and having both columns make up primary key; then most databases would be able to provide the sequence.

However this leads to the question if your primary key should have a meaning or not; Y suggest that there is some meaning in the part of the key (otherwise you would be content with a plain integer id).

0

精彩评论

暂无评论...
验证码 换一张
取 消