【问题标题】:Can you Chain Multiple Do Statements for different Where Conditions in SQlite Upsert Statement您能否在 SQlite Upsert 语句中为不同的 Where 条件链接多个 Do 语句
【发布时间】:2022-01-27 12:11:27
【问题描述】:

您好,我是 sqlite 新手,我想在 SQLite 中运行一个 Upsert 命令。这是在 C# 函数中运行的命令的 sn-p:

$@"INSERT INTO {table} (ToolType, TdxFolderPath, LastProcessedDateFolder, 
                LastProcessedTimeFolder, TdxFileName, LastTriedTimeStamp, Status, ErrorType, ErrorMessage, RetryCount)
                Values (@ToolType, @TdxFolderPath, @LastProcessedDateFolder, @LastProcessedTimeFolder, @TdxFileName,
                @LastTriedTimeStamp, @Status, @ErrorType, @ErrorMessage, @RetryCount)
                    ON CONFLICT (TdxFileName) 
                    DO UPDATE SET ErrorType=excluded.ErrorType, ErrorMessage=excluded.ErrorMessage, RetryCount = RetryCount + 1
                        WHERE excluded.ErrorMessage = ErrorMessage
                    DO UPDATE SET ErrorType=excluded.ErrorType, ErrorMessage=excluded.ErrorMessage, RetryCount = 0
                        WHERE excluded.ErrorMessage != ErrorMessage";

表变量是一个名为“ErrorLog_Items”的表,对 id 和 TdxFileName 具有唯一性约束。如果文件名已经存在,我想对几列进行更新。但是,如果文件名已经存在,我插入的错误消息可能与表中现有的错误消息相同。在这种情况下,我只想更新一些列并增加重试次数。

但是,如果新的错误消息与表中现有的错误消息不同,我想将 retrycount 重置为 0,并按照上面的命令更新某些列。

有没有办法在一个查询中做到这一点?还是需要多次查询?

【问题讨论】:

    标签: c# sqlite case upsert system.data.sqlite


    【解决方案1】:

    您可以使用CASE 表达式来做到这一点:

    .....................................
    ON CONFLICT(TdxFileName) 
    DO UPDATE SET ErrorType = excluded.ErrorType, 
                  ErrorMessage = excluded.ErrorMessage, 
                  RetryCount = CASE WHEN excluded.ErrorMessage = ErrorMessage THEN RetryCount + 1 ELSE 0 END
    

    并且不需要WHERE 子句。

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2016-09-18
      • 2012-01-26
      • 1970-01-01
      • 2015-09-16
      相关资源
      最近更新 更多