How to stop allowing same Primary Key

Go To StackoverFlow.com

0

Hi guys am using MVC3 and will like to know how to stop the same primary key to be entered within my application. I have my primary key set as NVARCHAR(100) and it can allow the console names I need a reg x of simlar validation to prevent users from entering the same name again thanks

If you need more info please ask

2012-04-05 21:59
by user1137472
It crashes when I try to enter the same name again, so that is why i need validation thank - user1137472 2012-04-05 22:02
which database system are u using - l--''''''---------'''''''''''' 2012-04-05 22:05
you want to use regex to query your db to see if a PK exists already - l--''''''---------'''''''''''' 2012-04-05 22:05


2

As I have recently answered, I recommend against using varchar() and nvarchar() columns as the primary key. They are slower on joins and QueryById() operations, and the temptation is to allow editing the value (which I also recommend against). Editing primary keys is bad because there is a clustered index on the column. If you change the values enough, you will skew the index and have to rebuild.

It is better to use an IDENTITY column (SQL Server) or SEQUENCE (Oracle) and set a UNIQUE constraint on the Name column. With the unique constraint, the database engine will throw an exception if the user tries to enter a duplicate name. Your code should catch the exception and present an appropriate error message to the user.

2012-04-05 22:06
by mgnoonan
I dont want to edit them it seems you havnt read the question, all i want is to stoo the user from entering the same ID agai - user1137472 2012-04-05 22:09
Perhaps you didn't read all of my answer.. - mgnoonan 2012-04-05 22:11
@user1137472 if you want answers, you need to clarify your question, i am voting for it to be close - l--''''''---------'''''''''''' 2012-04-05 22:12


0

I don't think you need a regex for that. Before adding the new record to the database, just perform a select and check if it is already there.

And like mgnoonan states, using varchars as primary keys is not generally good practice. Every time I've ever come across it, it eventually caused problems.

2012-04-06 04:07
by SouthShoreAK
Ads