Usage for "dynamic" UPDATE queries?
Closed this issue · 1 comments
I understand that this function allows me to write "dynamic" insert queries, given an array of column names and one with the corresponding values:
let query = format(
INSERT INTO sometable(%I) VALUES(%L);, arrColumn, arrValue);
However, how can I do the same with an UPDATE query where the syntax uses pairs (... SET column1=value1, column2=value2
, ...)?
I'm sure there must be a way but didn't find yet. Thanks in advance for your help.
I used like this
`
import Format from 'pg-format';
// ...
const sampleObject = {
id: 1,
name: sample,
code: sample_code
}
let sets = [];
for (let key in sampleObject) {
sets.push(Format('%I = %L', key, sampleObject[key]));
}
let setStrings = sets.join(',');
const query = Format(UPDATE equipment SET %s WHERE id = %L
, setStrings, eq.id);
const result = await client.query(query);
`