Skip to main content
 首页 » 编程设计

C# .Net3.5 将数据添加到 SQL Server 2005 数据库(如果它尚不存在并且是否更新它)

2024年02月24日17jpfss

你好,这是第一次玩 SQL!

我有下面的代码可以正常工作,但我需要使用 CustomerName 和 Product 来检查条目是否已经在数据库中,如果它在数据库中更新其他字段,如果不插入所有数据。

我该怎么做?

下面是我用来插入新记录的代码:

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 2005 结缘了吗?如果不是,我会建议查看 SQL 2008,因为它使用 MERGE 命令解决了这个问题。 如果您处于无法使用 SQL 2008 的情况,那么只需将这些命令包装在更多 SQL 代码中即可。

IF EXISTS (<Preform your Check>) 
BEGIN 
    Update ... blah blah 
END 
ELSE 
BEGIN 
    INSERT ()... 
END