【问题标题】:Insert new row to Database table if two fields does not match, otherwise sum value in certain column如果两个字段不匹配,则向数据库表插入新行,否则在某列中求和
【发布时间】:2020-11-17 01:31:16
【问题描述】:

我在数据库表中有数据:

添加数据的方法如下:

    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并将其与Database Table中现有的TimeSpent相加,而不输入新行。

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

【问题讨论】:

  • 在插入之前需要一个 Select 方法。如果用户名是主键,则您需要使用更新而不是插入(除非它是新帐户)。

标签: c# sql


【解决方案1】:

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

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

或者,您可以创建一个查询方法并首先调用它,然后再调用AddRecordToDatatable

就我个人而言,我会使用诸如 EF Core 或者最好是 NHibernate 之类的 ORM 来完成所有这些 CRUD 操作。但这一切都取决于要求、限制等。

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2017-03-23
    • 2020-03-22
    • 2016-01-14
    相关资源
    最近更新 更多