【问题标题】:Updating a column by using CASE expression throwing ERROR: column "external_uuid" is of type uuid but expression is of type boolean使用 CASE 表达式更新列抛出错误:列“external_uuid”是 uuid 类型,但表达式是布尔类型
【发布时间】:2022-01-23 03:31:54
【问题描述】:

我有一个表,我想在其中更新列 external_uuid,前提是该列已经没有值:

private const val updateSql = """
  update customer
  set
      external_id = :externalId,
      external_uuid = CASE when external_uuid is null then external_uuid = :externalUuid END,
      name = :name,
      address = :address,
      zip_code = :zipCode,
      zip_area = :zipArea,
      country_code = :countryCode,
      is_deleted = :markedForRemoval
  where is_deleted = false AND (external_uuid = :externalUuid OR (external_id = :externalId AND external_subcustomer = :subCustomer))
"""

但是,如果我进行这样的更新,我会收到错误:

 ERROR: column "external_uuid" is of type uuid but expression is of type boolean

如何在更新时有条件地仅设置一列?

【问题讨论】:

    标签: sql postgresql sql-update case coalesce


    【解决方案1】:

    您的CASE 表达式返回此布尔表达式的结果:

    external_uuid = :externalUuid
    

    可能是truefalse,不能存储在定义为uuid 的列中,这就是您收到错误的原因。

    你应该这样写:

    external_uuid = CASE when external_uuid is null then :externalUuid else external_uuid END
    

    或:

    external_uuid = coalesce(external_uuid, :externalUuid)
    

    【讨论】:

    • 感谢您的回答!我可以问你为什么当我用相同的值更新它时更新不起作用,例如,如果我有set external_uuid = :externalUuid,我会收到一个错误:ERROR: duplicate key value violates unique constraint, Key external_uuid already exists。当我更新 uuid 与现有 uuid 匹配的行时会发生这种情况,但如果我使用 coalesce(external_uuid, :externalUuid) 它可以工作。当在这两种情况下使用相同的值更新列时,前者为什么不起作用,或者合并不更新它,该列不为空?
    • 不,我不是说CASE表达式,只是直接设置external_uuid = :externalUuid,如果您更新的值与数据库中的现有值相同,那与coalesce(external_uuid, :externalUuid)有何不同?为什么投掷unique constraint errorcoalesce() 不是?
    • @Ludwig 你确定:externalUuid 具有与其更新的行完全相同的值吗?如果是,您能否在小提琴中重现该问题:dbfiddle.uk/…
    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 2015-04-22
    • 2011-12-18
    • 2023-02-09
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多