duankuiyuant3940 2017-01-14 05:57
浏览 261
已采纳

提供的值不为空字符串时更新MariaDB列

I am currently working on a Golang application that talks to a MariaDB database. My service will take in a *User and attempt to update the matching record.

For example:

func (d *database) UpdateUser(user *User) error {
    stmt, err := d.Prepare(`UPDATE Users
        SET FirstName=?, LastName=?, Email=?, Address1=?, Address2=?,
            City=?, State=?, Country=?, PostalCode=?
        WHERE Id=?`)
    if err != nil {
        return err
    }

    _, err := res, err := stmt.Exec(user.FirstName, user.LastName, user.Email,
        user.Address1, user.Address2, user.City, user.State, user.Country, 
        user.PostalCode, user.Id)
    return err
}

However, I do not want to update fields that aren't supplied. I am looking for something closer to this, where it would not update the value if the provided one is an empty string:

`UPDATE Users
 SET FirstName=? OR FirstName, LastName=? OR LastName, Email=? OR Email, 
     Address1=? OR Address1, Address2=? OR Address2, City=? OR City, 
     State=? OR State, Country=? OR Country, PostalCode=? OR PostalCode
 WHERE Id=?`

I have seen that SQL allows for updating using a CASE statement, but I do not see a way to use this without providing the same variable to the Exec() several times.

  • 写回答

1条回答 默认 最新

  • duancha1065 2017-01-14 06:00
    关注

    Like this

    UPDATE Users
    SET FirstName = case when ? is null then FirstName else ? end
    

    or to pass each parameter just once

    UPDATE Users
    SET FirstName = coalesce(?, FirstName)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算