Sorry if this is a dupe -- I searched for similar questions, but they all seemed to be along the lines of conditional updates where you can use CASE statements to set a column to one of several values.
I've got a SQL UPDATE statement, but there are two reasons why I would want it to NOT update:
- the item isn't found (causing rowsUpdated to be 0)
- if a condition is met
I'd like to differentiate between these two states somehow, which is why I can't just put the condition in the WHERE clause.
It currently looks something like this:
UPDATE MY_TABLE t
SET t.TITLE = :TITLE,
t.TYPE = :TYPE,
t.STATE = :STATE,
t.UPDTIME = :UPDTIME
WHERE t.ITEM_ID = :ITEM_ID
AND exists (SELECT t.ITEM_ID
FROM MY_TABLE t, USERINFO ui
WHERE ui.USERID = t.USERID
AND ui.USERNAME = :USERNAME
AND t.ITEM_ID = :ITEM_ID);
That will return 1 if it finds (and updates) an item in MY_TABLE that matches the given USERNAME and ITEM_ID, or 0 if it doesn't.
I'd like to add something so that it doesn't update if t.STATE = 'READ_ONLY', but so that it does something to differentiate that condition from the "that item doesn't exist" condition. Maybe throw an error of some sort?
I could run a SELECT statement before my update to make sure that item's state isn't READ_ONLY, but that seems wasteful. Is there a better way?
t.UPDTIME = CASE WHEN t.STATE = 'READ_ONLY' THEN 1/0 ELSE :UPDTIME END. The1/0should throw a division by zero you can catch.