I like to do construct a compare and swap operation so that it can be included in a batched transaction where if the cas statement fails, the rest of the statements will also fail.
This statement will update if time is 0
but doesn't throw an error if time is not 0
:
UPDATE account
SET time = '1'
WHERE id = (
SELECT id FROM account WHERE id = 'id-0' and time = '0' LIMIT 1
) RETURNING id
I want to add something like this
IF NO DATA THEN
RAISE EXCEPTION 'cas ';
END IF;
but not sure how to do it.
If you cannot use a plpgsql block for whatever reason, you can force a division by zero:
UPDATE account
SET time = '1'
WHERE id = (
SELECT id FROM account WHERE id = 'id-0' and time = '0' LIMIT 1
)
AND 1/(select count(*) from account where id = 'id-0' and time = '0') is not null
RETURNING id;
This is like stopping the bicycle I'm riding by jamming a stick in the front wheel spokes.
This works for me:
DO $$
DECLARE
v_id TEXT;
BEGIN
UPDATE "account"
SET (id, name) = ('t1', 'world')
WHERE id = ( SELECT id FROM "account" WHERE "id" = 't1' AND "name" = 'hello' LIMIT 1)
RETURNING id INTO v_id;
IF count(v_id) = 0
THEN RAISE EXCEPTION 'Cas Error for (account, t1)';
END IF;
END $$
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.