I have the following:
JavaScript
x
$query = $db->prepare("UPDATE name SET one=?,two=?,three=? WHERE id = ?");
$query->bindParam(1, $one);
$query->bindParam(2, $two);
$query->bindParam(3, $three);
$query->bindParam(4, $id);
one
and three
should always be updated.
However, how can I update two
only if it is null/empty?
I can do this in a separate command, though how can I achieve this in one prepared statement?
I am using SQLite3
Advertisement
Answer
Use a CASE
expression for column two
:
JavaScript
UPDATE name
SET one=?,
two=CASE WHEN two IS NULL THEN ? ELSE two END,
three=?
WHERE id = ?
Or with COALESCE()
:
JavaScript
UPDATE name
SET one=?,
two=COALESCE(two, ?),
three=?
WHERE id = ?