简体   繁体   English

如果存在更新,否则插入

[英]if exists update else insert

I want to know if the next piece of code is correct: 我想知道下一段代码是否正确:

 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);

All the parameters are correct that I want to insert but it seems this piece of code doesn't do the insert or update.Do you have any suggestions?it's a sql query combined with c#.. 我想插入的所有参数都是正确的,但是似乎这段代码没有执行插入或更新操作。您有什么建议吗?这是与c#结合使用的sql查询。

Inspect the string that's created by that command: some words need spaces between them. 检查该命令创建的字符串:某些单词之间需要空格。

 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);

Description 描述

No because you select count that has always a value. 否,因为您选择的count始终是一个值。

select a column or * instead. 选择一列或*

Sample 样品

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);

您为什么不使用MERGE命令?

You can try executing the query in SQL Server Management Studio window first. 您可以先尝试在SQL Server Management Studio窗口中执行查询。 This will give you an easy way to debug the things 这将为您提供调试事物的简便方法

我认为“ else”语句之间缺少空格还请确保您已在values部分提供了所有列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM