I’ve been battling with this for too long so I’m here to ask for help…
I have a MySQL stored procedure that I want to do the following:
given an ‘id’ and a ‘username’ for a given record
- if id does not exist in table then create record
- else if id exists and username is not the same as what exists then update record
- else do nothing
I’ve tried the following:
BEGIN
DECLARE doCreate INT;
DECLARE doUpdate INT;
SELECT COUNT(*) INTO doCreate FROM app_user WHERE id=1;
IF (doCreate > 0) THEN
SELECT COUNT(*) INTO doUpdate FROM app_user WHERE id=1 AND username='other';
END IF
IF(doCreate = 0) THEN ---SYNTAX ERROR ON THIS LINE---
SELECT 'CREATE';
ELSE IF(doUpdate = 0) THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END IF
END
I’ve also tried replacing the if-elseif-else block with a case statement but get the same result…
CASE ---ERROR ON THIS LINE---
WHEN doCreate = 0 THEN
SELECT 'CREATE';
WHEN doUpdate = 0 THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END
- I seem to get a syntax error on anything that comes after the first END IF, so that’s the first problem that occurs…
Any help would be appreciated – I’m sure there’s a better way to do this.
I believe you’ll need to terminate the
END IFs with;, and internallyELSEIFshould be one word. Otherwise, anotherEND IFis needed, but not found.Look over the MySQL
IF/ELSEsyntax reference for various usage examples.