简体   繁体   中英

Updated row in table only by valid values and skip undefined values

I have next method which updates row:

  await db.query(`
    UPDATE some_table 
    SET value1 = $1, value12 = $2, value2 = $3
    WHERE id $5
  `, [value1, value2, value3, id]);

How to modify this query, that it will skip for example value2 and value3 , if they are undefined and update only column value1 ?

Shortcircuit is the way to go, basically the set is only added if value1-3 are not undefined

let sql = `UPDATE some_table 
           SET ${$value1 !== undefined ? 'value1 = $value1, ' : ''}
               ${$value2 !== undefined ? 'value12 = $value2, ' : ''}
               ${$value3 !== undefined ? 'value3 = $value3, ' : ''}`;
sql.slice(0,-2); // remove last space and comma
sql += ' WHERE id ${id}';
await db.query(sql);

Don't recommend using c style to add parameters ($1, $2 etc.) it makes it harder to read the code.

You can use a CASE expression:

UPDATE some_table 
  SET value1 = $1, 
      value12 = case when when value12 = 'undefined' then $2 else value12 end, 
      value2 = case when value2 = 'undefined' then $3 else value2 end
WHERE id = $5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM