首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入与更新

问插入与更新
EN

Stack Overflow用户
提问于 2012-03-07 18:27:45
回答 6查看 1K关注 0票数 1

我有以下疑问:

代码语言:javascript
复制
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,我能做到吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-03-07 18:43:25

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

代码语言:javascript
复制
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);   

这应该会起作用。

票数 2
EN

Stack Overflow用户

发布于 2012-03-07 18:34:22

由于涉及大量脚本(这将是混乱的内联!),这可能是在存储过程中完成的最好方法。

将您的参数传递给存储过程,并执行以下操作:

代码语言:javascript
复制
IF EXISTS(SELECT cnp FROM Raspunsuri WHERE cnp=@cnp)
BEGIN
    UPDATE ...
    WHERE cnp=@cnp
END
ELSE
BEGIN
    INSERT INTO....
END

假设@cnp是您的主键

然后,您的SqlCommand将更改为:

代码语言:javascript
复制
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);
票数 6
EN

Stack Overflow用户

发布于 2012-03-07 18:35:32

您可以使用SQL Server中的@@ROWCOUNT功能。

代码语言:javascript
复制
UPDATE Raspunsuri SET (...) WHERE PrimaryKeyColumn='YourValue'
IF @@ROWCOUNT=0
    INSERT INTO Raspunsuri VALUES (...)

类似的问题:Insert / Update to Sql

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9599709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档