2

I need to change rows in my DB using 2 arrays, first stores names of rows which i need to change, second stores val. I've added the code , to understand what I want to do. Can i do it with 1 request to my DB

func update_1(){
    key := []string{"Name1", "Name2", "Name4"}
    val := []string{"1", "2", "4"}
    for i, _ := range key{
        _, err := db.Exec("UPDATE table SET val = $1 WHERE name = $2",val[i], key[i])
        if err != nil {
            errorLog.Println(err)
            return
        }
    }
}
kokolen
  • 23
  • 4

1 Answers1

3

You can pass the arrays into a Postgres query as parameters. Then it is a simple unnest() and update:

update t
    set val = u.val
    from unnest(:ar_names, :ar_vals) u(name, val)
    where t.name = u.name;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    db.Exec("update test set val = u.val from unnest($1::bigint[], $2::character varying[]) u(name, val) where test.name = u.name", pq.Array([]int{1, 3}), pq.Array([]string{"228", "228"})) my final request in golang – kokolen May 02 '21 at 18:39