I want to perform a check if the value that I want to update already exists in a table before updating a column.
For example: if I have table called Tokens , with column called refresh_token , and token . I only want to update a blank refresh_token only if their exists no other refresh_token with the same value.
I have this:
IF (NOT EXISTS(SELECT * FROM Tokens WHERE refresh_token = 'C08Rbs'))
BEGIN
UPDATE Tokens SET refresh_token='C08Rbs' WHERE id='2'
END
END;
but it is returning an error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (NOT EXISTS(SELECT * FROM Tokens WHERE refresh_token = 'C08Rbs' at line
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (NOT EXISTS(SELECT * FROM Tokens WHERE refresh_token = 'C08Rbs' at line
1
How should I do this?
NOTE: I am not using a stored procedure. I want to do this using one query.
And is there a way I can do it using an if-else statement??. Because if to execute a statement if the value exists
You can do this in one statement:
UPDATE Tokens
SET refresh_token = 'C08Rbs'
WHERE id = '2' AND
NOT EXISTS (SELECT 1 FROM Tokens WHERE refresh_token = 'C08Rbs');
EDIT:
Ooops. In MySQL, you need to do this with a join
:
UPDATE Tokens t CROSS JOIN
(SELECT COUNT(*) as cnt
FROM Tokens
WHERE refresh_token = 'C08Rbs'
) tc
SET refresh_token = 'C08Rbs'
WHERE id = '2' AND tc.cnt = 0;
Try this:
IF (SELECT tocken_id FROM Tokens WHERE refresh_token = 'C08Rbs') IS NOT NULL THEN
BEGIN
UPDATE Tokens SET refresh_token='C08Rbs' WHERE id='2'
END
END IF;
Where tocken_id
is unique field or any field in Tockens
table.
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.