• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 201
  • Last Modified:

inserting non duplicate data

hi all,

I have an asp.net page in which users insert data to the database. my question is that how can i search if the data is a duplicate and if so show a message that says that the data is already in the db. if not just insert the data and show a message that says it is successfully enterd

1 Solution
One way to do this is to have a primary key in the database or a constraint on the table.  Just try to do the insert and catch the constraint violation, if you see that then you can display the message that the data is already entered, otherwise it will have inserted.
Generally speaking:

1. compare it to a local dataset of data that matches the data in the database

2. do a query against the database to see if values user wants to add already exist

3.  put constraints on the database that don't allow duplicate data, which will cause the insert to fail.  By catching the exeception, you would then know the data already exists.
If you want to check if the data already exists you can write a SQL query like

Select Count(*) from <Table_Name>
where <column-name1> = ' value1' and <column-name2> = ' value2'

For Eg.
The testtable has 2 columns id,name.

select count(*) from testtable where id = 2 and name = '2'

Use the command object ExecuteScalar method to get the count of number of rows. If the count is 1, then the row already exists. If not you can then enter the values into the database.
jemigossayeAuthor Commented:
hi sirdon,
how can i count the executescalar()
what i am doing now is trying to cast it to an int and assign it to an int var
and then with in if else i am will try to insert it

hi  jemigossaye,
Yep that is the way you have to do it. Type cast it to an int and then check the value of the int.

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now