C# primary key

ITsolutionWizard
ITsolutionWizard used Ask the Experts™
on
I would like to create unique identifier like below.

1. h111111

the format is
1. Must start "h"
2. with 5 numbers only

the 5 numbers can be random, but once it is created, it can't be duplicated.

is it possible?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
Yes possible..

SQL Solution , try

SELECT CONCAT( 'h' , RIGHT(RAND(),5) )
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
One more option for < SQL Server 2012

SELECT 'h' + CAST(CONVERT(NUMERIC(12,0),RAND() * 99999) + 10000 AS VARCHAR(7))
HuaMin ChenProblem resolver

Commented:
By Unique constraint to the column, you can achieve this.
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Rajkumar GsSoftware Engineer

Commented:
Since you have to generate next ID in a custom format, better go for sequence approach to make sure no duplicates.
Try any of the explained approach here
http://www.sqlteam.com/article/custom-auto-generated-sequences-with-sql-server

Author

Commented:
Can we use it without sql?
Database Expert
Awarded 2016
Top Expert 2016
Commented:
Try below options..

Random rnd = new Random();
        string str1 = "H" + rnd.Next().ToString().Substring(0, 5);


        char[] ch = Guid.NewGuid().ToString().Where(x => char.IsNumber(Convert.ToChar(x))).Take(5).ToArray();
        string str2 = "H" + (new string(ch));

--

Open in new window


Enjoy!!
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
Yes you can also create unique constraints..Approach below.

DataTable at ;

UniqueConstraint aUnique =  new UniqueConstraint(
new DataColumn[] { at.Columns["ID"], at.Columns["Name"] });

at.Constraints.Add(aUnique);
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
the 5 numbers can be random, but once it is created, it can't be duplicated.
Choose one of the above solutions to implement the generation of the values but to assure that's no duplicates you'll need to create an unique index on the field:
CREATE UNIQUE INDEX IndexName ON TableName (ColName)

Open in new window


or create a Primary Key if you don't have one in the table:
ALTER TABLE TableName  
ADD CONSTRAINT PK_TableName_ColName PRIMARY KEY (Colname)

Open in new window

Author

Commented:
This is the best solution. Without using SQL is perfect. Good Job

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial