3

I would like to insert data into my database if one value doesn't exist in my database.

I've got this code:

try
{
    SQLConnection.Open();

    string sql = "INSERT INTO shop (title, price, information) values (@chp1, @chp2,@chp3)";

    SqlCommand cmd = new SqlCommand(sql, SQLConnection);
    cmd.Parameters.AddWithValue("@chp1", title);
    cmd.Parameters.AddWithValue("@chp2", price);
    cmd.Parameters.AddWithValue("@chp3", information);

    cmd.ExecuteNonQuery();
}

I try to insert in my database, if the value "title" doesn't exist in my database.

In stackoverflow I've founded this answer with IF EXISTS, but I don't see how to use it ...

Thanks in advance for your answer :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
pi-2r
  • 1,259
  • 4
  • 27
  • 52

1 Answers1

9
string sql = 
    "IF NOT EXISTS (SELECT 1 FROM shop WHERE title = @chp1)
    BEGIN
       INSERT INTO shop (title, price, information) values (@chp1, @chp2,@chp3)
    END";

Try the above

TGH
  • 38,769
  • 12
  • 102
  • 135