如果存在则更新其他插入

时间:2012-03-14 08:55:39

标签: c# asp.net sql-server

我想知道下一段代码是否正确:

 SqlCommand cmd = new SqlCommand(
   "IF NOT EXISTS(SELECT count(*) from Raspunsuri where id_intrebare=2)" +
   "Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune)" +
   "else" +
   "UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

我要插入的所有参数都是正确的,但似乎这段代码没有插入或更新。你有什么建议吗?这是一个结合c#的SQL查询..

5 个答案:

答案 0 :(得分:4)

检查该命令创建的字符串:某些字在它们之间需要空格。

 SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT 1 from Raspunsuri where id_intrebare=2)" +
                " Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune)" +
                " else" +
                " UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

答案 1 :(得分:3)

描述

不,因为您选择始终具有值的count

选择一列或*代替。

示例

SqlCommand cmd = new SqlCommand(
   "IF NOT EXISTS(SELECT id_intrebare from Raspunsuri where id_intrebare=2) " +
   "Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune) " +
   "else " +
   "UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

答案 2 :(得分:1)

为什么不使用MERGE命令?

答案 3 :(得分:1)

您可以先尝试在SQL Server Management Studio窗口中执行查询。这将为您提供一种简单的方法来调试事情

答案 4 :(得分:0)

我认为“else”语句之间缺少空格 还要确保已提供值部分

中的所有列