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

标签 c# sql sql-server-2005 .net-3.5

你好,这是第一次玩 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

关于C# .Net3.5 将数据添加到 SQL Server 2005 数据库(如果它尚不存在并且是否更新它)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4159893/

相关文章:

php - 在 5 个月的时间跨度内,只应将 3 个用户插入数据库

mysql - 如何优化多次使用变量的 MySQL 查询?

c# - 我不想在存储过程中转换的复杂 SQL

c# - 如何在 gRPC 和 ASP Net Core 3.0 中使用 ssl 证书?

c# - 设计 View 未在 Visual Studio 2015 中打开

c# - 为这个聊天应用程序使用 Ajax(可能与 Web 服务一起使用)

sql - 显示存储过程

sql - 如何获取SQL组查询的第一行?

SQL Pivot 基于两列之间的值

c# - 2 外键作为主键使用 EF Core 2.0 Code First