我有以下疑问:
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();
}我需要的是查看表中是否有任何记录,如果有,那么update,else,insert it.How,我能做到吗?
发布于 2012-03-07 18:43:25
您可以在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); 这应该会起作用。
发布于 2012-03-07 18:34:22
由于涉及大量脚本(这将是混乱的内联!),这可能是在存储过程中完成的最好方法。
将您的参数传递给存储过程,并执行以下操作:
IF EXISTS(SELECT cnp FROM Raspunsuri WHERE cnp=@cnp)
BEGIN
UPDATE ...
WHERE cnp=@cnp
END
ELSE
BEGIN
INSERT INTO....
END假设@cnp是您的主键
然后,您的SqlCommand将更改为:
SqlCommand cmd = new SqlCommand("sp_StoredProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
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);发布于 2012-03-07 18:35:32
您可以使用SQL Server中的@@ROWCOUNT功能。
UPDATE Raspunsuri SET (...) WHERE PrimaryKeyColumn='YourValue'
IF @@ROWCOUNT=0
INSERT INTO Raspunsuri VALUES (...)类似的问题:Insert / Update to Sql
https://stackoverflow.com/questions/9599709
复制相似问题