INSERT与UPDATE [英] INSERT vs. UPDATE
本文介绍了INSERT与UPDATE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询:
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();
}
我需要的是看是否有表中的任何记录,如果没有比别人更新插入it.How我能做到这一点?
What i need is to see if there is any record in the table and if there is than update else insert it.How can I achieve that?
推荐答案
您可以使用SQL中的存在的功能。例如:
You can use the Exists function in SQL. For Example
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);
这是应该做的伎俩
这篇关于INSERT与UPDATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文