c# - 如果两个字段不匹配,则将新行插入数据库表,否则在特定列中求和值

标签 c# sql

我在数据库表中有数据:

enter image description here

添加数据的方法如下:

    public static void AddRecordToDatatable(string WindowTitle, int TimeSpent,
        DateTime DateToday, string Project, string Username)
    {
        string sql = @"INSERT INTO dbo.Log (WindowTitle,TimeSpent,DateToday,Project,Username)" + 
                            " VALUES (@WindowTitle,@TimeSpent,@DateToday,@Project,@Username)";

        // Create the connection (and be sure to dispose it at the end)
        using (SqlConnection cnn = new SqlConnection(DBconnectionString))
        {
            try
            {
                // Open the connection to the database. 
                // This is the first critical step in the process.
                // If we cannot reach the db then we have connectivity problems
                cnn.Open();

                // Prepare the command to be executed on the db
                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    // Create and set the parameters values 
                    cmd.Parameters.Add("@WindowTitle", SqlDbType.NVarChar).Value = WindowTitle;
                    cmd.Parameters.Add("@TimeSpent", SqlDbType.Int).Value = TimeSpent;
                    cmd.Parameters.Add("@DateToday", SqlDbType.DateTime).Value = DateTime.Now.Date;
                    cmd.Parameters.Add("@Project", SqlDbType.NVarChar).Value = Project;
                    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Username;

                    // Let's ask the db to execute the query
                    int rowsAdded = cmd.ExecuteNonQuery();
                    if (rowsAdded > 0)
                    {
                        //MessageBox.Show("Row inserted");
                    }
                    else
                    {
                        // This should never really happen, but let's leave it here
                        //MessageBox.Show("No row inserted");
                    }
                }
                cnn.Close();

            }
            catch (Exception ex)
            {
                // We should log the error somewhere, 
                // for this example let's just show a message
                MessageBox.Show("ERROR:" + ex.Message);
            }
        }
    }

在将数据输入数据库表之前如何检查现有记录,并在存在某个值时对其求和?

因此,基本上检查是否 WindowTitle = WindowTitleDateToday = DateToday,如果这两者匹配,则获取 TimeSpent 并将其与数据库表中现有的 TimeSpent 相加,而无需输入新的行。

我尝试在 INSERT 之后测试 ON DUPLICATE KEY UPDATE WindowTitle = @WindowTitle, DateToday = @DateToday 但 Visual Studio 在调试器中针对此类命令给出错误指向 ON(ON 附近的语法不正确)。另外,我不确定 ON DUPLICATE 是否是这种情况的最佳方法。

最佳答案

您需要扩展 SQL 来检查您认为可能存在的记录是否存在。

IF EXISTS (SELECT 1 FROM dbo.Log WHERE WindowTitle = @WindowTitle AND DateToday = @DateToday)
BEGIN
    --UPDATE HERE
END
ELSE
BEGIN
   -- INSERT HERE
END

或者,您可以创建一个查询方法并在调用AddRecordToDatatable之前先调用该方法

我个人会使用 ORM(例如 EF Core 或最好是 NHibernate)来完成所有这些 CRUD 操作。但这一切都取决于要求、限制等。

关于c# - 如果两个字段不匹配,则将新行插入数据库表,否则在特定列中求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862305/

相关文章:

c# - 如何从脚本在 Unity 中创建窗口并将其附加到现有选项卡?

C# 父/子数据结构可用性?

c# - HTML.EditorFor 小数点后 3 位

c# - 在 Excel 上执行多个更新命令

mysql - 相同的存储过程,相同的表,不同的数据库给出不同的结果

mysql select 查询错误

c# - 两个表深左外连接

c# - XML 序列化 : The type of the argument object 'Sw' is not primitive

MySQL 避免 WHERE/AND 中的子查询重复

sql - PostgreSQL:仅当元素唯一时才将元素附加到 jsonb 数组