There are two ways.
One: create a select or select count(*) with the same parameters and check if there are any results > 0 returned. Don't perform the second insert unless the select has no results
Two: (the correct way) You can use
Select
even if you only have variables to insert. You can use this syntax to add a
Where
clause
Add a clause on the insert to avoid duplicates:
s = @"
insert into Cars (Car_id , Car_No, Car_No_2, Car_shs, Car_Motor)
Select @Car_id , @Car_No, @Car_No_2, @Car_shs, @Car_Motor
Where not exists (
select *
from Cars
where
Car_id = @Car_id
and Car_No = @Car_No,
and Car_No_2 = @Car_No_2
and Car_shs = @Car_shs
and Car_Motor = @Car_Motor)
"
sCommand = new SqlCommand(s, con);
con.Open();
sCommand.Parameters.AddWithValue("@Car_id", txt_Car_id.Text);
sCommand.Parameters.AddWithValue("@Car_No", txt_Car_No.Text);
sCommand.Parameters.AddWithValue("@Car_No_2", txt_Car_No_2.Text);
sCommand.Parameters.AddWithValue("@Car_shs", txt_Car_shs.Text);
sCommand.Parameters.AddWithValue("@Car_Motor", txt_Mator_No.Text);
sCommand.ExecuteNonQuery();
This will not insert if it exists.
You can check if it was inserted by checking the return value of
sCommand.ExecuteNonQuery()
. It returns a count of the rows affected:
var recordsAffected = sCommand.ExecuteNonQuery();
return recordsAffected == 1;
Hope that helps ^_^
Andy