你好,现在第一次玩SQL!C#.Net3.5添加数据到SQL Server 2005数据库如果它不存在,并且它更新它?
我有下面的代码工作正常,但我需要检查,如果条目已经在数据库中使用CustomerName和产品匹配,如果它在数据库中更新其他字段,如果不插入所有数据。
我该怎么做?
下面是我用它来插入新记录代码:
DateTime FirstDateSeen = new DateTime();
FirstDateSeen = DateTime.Now.Date;
DateTime LastDateSeen = new DateTime();
LastDateSeen = DateTime.Now.Date;
SqlConnectionStringBuilder MySqlConnection = new SqlConnectionStringBuilder("MY CONNECTION");
SqlConnection db = new SqlConnection(MySqlConnection.ToString());
try //sql string for first seen
{
string sqlIns = "INSERT INTO Customer (Product, Version, CustomerName, CustomerPostcode, FirstSeen, LastSeen)" +
"VALUES (@Product, @Version, @CustomerName, @CustomerPostcode, @FirstSeen, @LastSeen)";
db.Open();
SqlCommand cmdIns = new SqlCommand(sqlIns, db);
cmdIns.Parameters.Add("@CustomerName", UniqueA);
cmdIns.Parameters.Add("@Product", AppName);
cmdIns.Parameters.Add("@Version", AppVer);
cmdIns.Parameters.Add("@CustomerPostcode", UniqueB);
cmdIns.Parameters.Add("@FirstSeen", FirstDateSeen.ToShortDateString());
cmdIns.Parameters.Add("@LastSeen", LastDateSeen.ToShortDateString());
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
}
catch (Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
db.Close();
}
是否存在等所有的SQL命令的一部分? (这不是C#!!) – Adrian 2010-11-11 22:50:34
@Adrian是的,人们给出的答案都是SQL(除了@ Hogan的异常捕获者的切线)。 – 2010-11-11 23:01:11