写一个golang函数,入参是一个slice和数据库表名,slice为struct类型,字段有tag叫db,这个函数的功能是根据入参拼接批量update sql。sql语句用case when,不要用循环
时间: 2024-05-08 16:16:59 浏览: 126
```
func GenerateBatchUpdateSQL(data interface{}, tableName string) (string, error) {
v := reflect.ValueOf(data)
if v.Kind() != reflect.Slice {
return "", errors.New("input data is not a slice")
}
if v.Len() == 0 {
return "", errors.New("input slice is empty")
}
t := v.Index(0).Type()
var fields, values string
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag.Get("db")
if tag != "" {
fields += tag + ","
values += "WHEN ? THEN " + tag + " "
}
}
fields = strings.TrimRight(fields, ",")
values = strings.TrimSpace(values)
sql := fmt.Sprintf("UPDATE %s SET ", tableName) + fields + " = CASE id " + values + " END"
return sql, nil
}
```
阅读全文