Insert into if not exist in C#

c#, insert, sql, sql-server, sql-server-2008

Solution

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

Problem

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 :)

Original source

Related problems