Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Sir,
In my project I want to know how to avoid the duplicate records when insert
into database
One of my form, there is state code and state name text fields.
I want to insert the same state code only once.
How can I avoid the same state code when one try to insert it again


The code is as follows to insert:
Actually I didn't write the code to avoid the duplicate once,because I don't know the code exactly


C#
SqlCommand cmd = new SqlCommand();
                            
String str = "insert into State(Code,Name)values ('" + 
              this.txtstatecode.Text + "','" + this.txtstatename.Text + "')";
cmd.CommandText = str;
cmd.Connection = conn;
cmd.ExecuteNonQuery();                               

DataTable dt = new DataTable();

String str1 = "select code,name from state";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str1;

SqlDataAdapter adp = new SqlDataAdapter(cmd);
SqlCommandBuilder cb = new SqlCommandBuilder(adp);
                               
adp.Fill(dt);
                                
bs.DataSource = dt;
statedg5.ItemsSource = bs;

adp.Update(dt);
this.datagrid.Items.Refresh();


[Modified: added pre tags and modified spacing in code]
Posted
Updated 8-Apr-10 7:49am
v2

I would suggest you to use IF NOT EXISTS condition in your query to check for already existence of records.

IF NOT EXISTS (SELECT CODE FROM STATE WHERE CODE = ????)
BEGIN
    --INSERT RECORD HERE
END


This way you will have a single call to database table.
 
Share this answer
 
v3
To check if a state and code exists, perform a select statement with a where clause specifying the state and code you are looking for.

If the select statement returns no records, it doesn't exist, so insert it into the database. If the select statement returns a record, do not insert it again as the state and code already exist.

example:

select code, name from state where code = '1234' and name = 'Smithville'

Another thing - you will need to remember to handle single quotes that exist in your state names when building your SQL string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900