C# primary key

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?
LVL 1
ITsolutionWizardAsked:
Who is Participating?
 
Pawan KumarDatabase ExpertCommented:
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!!
0
 
Pawan KumarDatabase ExpertCommented:
Yes possible..

SQL Solution , try

SELECT CONCAT( 'h' , RIGHT(RAND(),5) )
0
 
Pawan KumarDatabase ExpertCommented:
One more option for < SQL Server 2012

SELECT 'h' + CAST(CONVERT(NUMERIC(12,0),RAND() * 99999) + 10000 AS VARCHAR(7))
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
HuaMin ChenSystem AnalystCommented:
By Unique constraint to the column, you can achieve this.
0
 
Rajkumar GsSoftware EngineerCommented:
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
0
 
ITsolutionWizardAuthor Commented:
Can we use it without sql?
0
 
Pawan KumarDatabase ExpertCommented:
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);
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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

1
 
ITsolutionWizardAuthor Commented:
This is the best solution. Without using SQL is perfect. Good Job
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.