ExecuteNonQuery不更新SQL Server

时间:2016-07-04 08:49:25

标签: c# sql-server

我正在使用这些行连接到sql server

SqlCommand scom = new SqlCommand(testing, conn);
scom.ExecuteNonQuery();

如果testing的值很简单:

string testing = "Insert INTO People (ID, Name) values (123,'Lara')"; 

它完美无缺。 但是,如果我使用类似的东西:

String testing = "Insert INTO People (ID, Name) values (123,'Lara')" +
                 " ON DUPLICATE KEY UPDATE Name = 'Lara'";

SQL服务器未更新,代码转到catch语句,如果我使用if exist它也不起作用。   以下是我的代码以获得更多说明:

SqlConnection conn = new SqlConnection("Data Source=ServerName;" +
    "Initial Catalog=DataBaseName;" +
    "Integrated Security=True;");

try
{
    conn.Open();
    string testing= "Insert INTO People (ID, Name) values (123,'Lara')";
    SqlCommand scom = new SqlCommand(testing, conn);
    scom.ExecuteNonQuery();
    MessageBox.Show("Saved! ");
}    
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    System.Windows.Forms.MessageBox.Show("Halted! ");
}
finally
{
    conn.Close();
}    

1 个答案:

答案 0 :(得分:0)

没有DUPLICATE KEY UPDATE等效,但MERGEWHEN MATCHED可能适合您

Inserting, Updating, and Deleting Data by Using MERGE