I'd like a simple example of a MySQL if, else, endif statement.
I want to do something like this (in Java):
SELECT COUNT(*) FROM `table` WHERE `userID` = 1
if(count == 0){
INSERT INTO `table` (`userID`,`A` ,`B`)VALUES ('1', '323', '232')
}
else{
UPDATE `table` SET `A` = '323', `B` = '232' WHERE `userID` =1
}
MySQL IF-THEN-ELSEIF-ELSE statement The syntax is given below: IF condition THEN statements; ELSEIF elseif-condition THEN elseif-statements; ... ELSE else-statements; END IF; Let's review each block.
IF color = red THEN dbms_output. put_line('You have chosen a red car') ELSE dbms_output. put_line('Please choose a color for your car'); END IF; If the Boolean expression condition evaluates to true, then the if-then block of code will be executed otherwise the else block of code will be executed.
Syntax. If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed. C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
MySQL has INSERT ON DUPLICATE KEY UPDATE
that allows you to update if the value already exist or Insert if not.
First you need to setup a UNIQUE
Constraint,
ALTER TABLE myTable ADD CONSTRAINT tb_uq UNIQUE (ID)
that's it if you want ID
to be unique. (This is just an example)
INSERT INTO tableName(userID, A, B)
VALUES (1, 323, 232)
ON DUPLICATE KEY
UPDATE A = 323,
B = 232
The if statement (in a stored block):
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Or the if function (in-line):
IF(expr1,expr2,expr3)
which works as: IF( condition, what_to_do_if_true, what_to_do_if_false ) The last part being the same as an 'else'. An if-else-if would need to be embedded like:
SELECT IF( id==1, "1", IF( ID==2, "2", "Neither" );
Which would do the same as this in most programming languages:
if( id == 1 ) {
print "1"
} elsif( id == 2 ) {
print "2"
} else {
print "Neither"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With