一尘不染

INSERT vs. UPDATE

sql

我有以下查询:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'1',@ip,@idsesiune)", con);

cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("@raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("@ip",ip);
cmd.Parameters.AddWithValue("@idsesiune", id_sesiune);

try
{
    con.Open();
    cmd.ExecuteNonQuery();
    Response.Redirect("User2.aspx");
}
catch (Exception ex)
{
    Console.WriteLine("Error:" + ex);
}
finally
{
    con.Close();
}

我需要查看表中是否有任何记录,是否有更新而不是其他插入。如何实现?


阅读 158

收藏
2021-03-10

共1个答案

一尘不染

您可以在SQL中使用Exists函数。例如

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);   
    SqlCommand cmd = new SqlCommand("if Exists(Select 1 from Raspunsuri where <your unique criteria>)\r\n" +
"Update Raspunsuri set <values you want to set> where <your unique criteria\r\n" +
"else\r\n" +
"INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'1',@ip,@idsesiune)", con);

    cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);   
    cmd.Parameters.AddWithValue("@raspuns", textbox1.Text);   
    cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());   
    cmd.Parameters.AddWithValue("@ip",ip);   
    cmd.Parameters.AddWithValue("@idsesiune", id_sesiune);

这应该够了吧

2021-03-10