Aritra Nath
Aritra Nath

Reputation: 21

How to restrict users from inputting duplicate values in a table?

I have a table with item names. In asp.net i have a textbox where users may enter new item to add in the table. I need to restrict the users to entering duplicate item name in the table. When user enter a text(item name) in the textbox, which is already present in the table and click on a save button, i need to display a message/validation that the item already exists. How do i do this??

Upvotes: 1

Views: 1909

Answers (4)

mehdi lotfi
mehdi lotfi

Reputation: 11571

You can use unique constraint and unique index on column Name to your table. SQL Server will then raise an exception when duplicate name entered.

Upvotes: 0

Akash KC
Akash KC

Reputation: 16310

You can execcute following query:

SELECT checking_col_name
FROM your_table
WHERE checking_col_name = your_textbox_value
GROUP BY checking_col_name
HAVING ( COUNT(checking_col_name) > 0 )

If above query return the row, then you can infer that the value already exist in the column of given table and hence you can apply the condition in your code accordingly.....

As Wiktor Zychla has suggested that above query may have problem when dealing with multiple user envrionment, I would recommend you to check Constraint.....You can have UNIQUE Constraint which ensures that there will be no duplicate row(will have only unique value)....If there executes query to insert duplicate value, it throws error which you can trace in your code and hence apply on your condition......

Upvotes: 0

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

Add a unique constraint to your table on the Name column. SQL Server will then raise an execption when someone tries to add a duplicate name. You have to deal with the exception in your client code showing a sensible message to the user.

Upvotes: 3

Erre Efe
Erre Efe

Reputation: 15557

You don't wrote any code so:

Assuming you're using Ajax you can check the DB for the item to not exists once the text property of the textbox change.

If you're using plain asp.net then you can try to add the item to the database and catch the exception. If there's an exception within your insert logic and its related to a duplicate key (error number 2601) then you invalidate the textbox visual.

Hope it serves.

Upvotes: 0

Related Questions