Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into if not exist in C# [duplicate]

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

like image 287
pi-2r Avatar asked Jan 26 '26 18:01

pi-2r


1 Answers

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

like image 164
TGH Avatar answered Jan 28 '26 08:01

TGH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!