Option 1
SQL Server already has an auto-increment feature that is both guaranteed to generate a unique ID and is efficient.
If you want to "add letters to that ID", the simplest solution is to add a separate varchar
field that contains those letters, and then format them for display as a single number in your application (either by using a SQL query to do so or string.Format.
ID | IDText Application Display
------------------ -----------------------
1 | MyLabel 1-MyLabel
2 | MyLabel 2-MyLabel
3 | FooBar 3-FooBar
4 | SomeText 4-SomeText
So, in the above, ID
would be an auto-increment int
field and IDText
would be a varchar
(or char
if you want a fixed length).
As you can see, even if the same string such as "MyLabel"
were added at the same time, you would get a different ID
to append to it so you in effect have a unique ID.
Option 2
Use a stored procedure to contain the following logic in a single transaction with BEGIN TRANSACTION/END TRANSACTION
:
- Query for the highest ID
- Add 1 to that ID
- Create a new record with the new ID
- Return that ID
The transaction will guarantee that the number cannot be duplicated. This is less efficient for creating IDs, but more efficient at looking them up than the 2-column approach.