Hi
I have below code . If already exists it should not be added
string constr = ConfigurationManager.ConnectionStrings["Cnn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO Category VALUES (@CategoryId,@CategoryName)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@CategoryId", data.id);
cmd.Parameters.AddWithValue("@CategoryName", data.snippet.title);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Thanks
Amit MohantyPosted Apr 10, 2024, 5:34 AM
You can modify your SQL query to check if the category already exists before attempting to insert it by using the IF NOT EXISTS clause.
Lalji DhameliyaPosted Apr 12, 2024, 12:48 PM
You can use the
MERGEstatement in SQL Server to achieve this. Here's how you can modify your code to useMERGE:Sam HobbsPosted Apr 10, 2024, 7:51 PM
When creating a table you can specify fields in tables as being unique. It is an option for fields in tables. You can alter the existing table to specify that specific fields must be unique.
The code provided here is good, it is good to avoid attempting to add a row that should not be added but if you never want duplicates of a field then the table should be created approriately.
Naimish MakwanaPosted Apr 10, 2024, 4:59 AM
Try below code:
Thanks