mardi 31 mars 2020

Define IF-THEN statements within labels

Following this question, consider that you want to do multiple things if a condition is met. pseudocode:

if condition then
    do things
else if other conditions then
    do other things
else
    other things
end if

From this page one could define the if statement within a dummy procedure:

DROP PROCEDURE IF EXISTS <procedure_name>();
DELIMITER $$

CREATE PROCEDURE <procedure_name>()
BEGIN
    IF (<conditions>) THEN
        -- do things
    ELSEIF (<conditions>) THEN
        -- do other things
    ELSE 
        -- other things
    END IF;
END$$

DELIMITER ;

<procedure_name>();

which is honestly the ugliest way of implementing an if statement I have ever seen in any programing language, ever!

This page suggests some one-liner if statement syntax in the form of

SELECT IF(<condition>, 'true message', 'false message');

to print out messages or nested

SELECT <fields>
IF (<condition>)
AS <custom_label>
FROM <table>

to only select rows from a table that meet a specific condition of a specific field/column.

Now I was wondering if it is possible to implement if statements in a more canonical way. For example, using labels to contain IF-THEN statements:

<label>: IF (<conditions>) THEN
    -- do things
ELSEIF (<conditions>) THEN
    -- do other things
ELSE 
    -- other things
END IF <label>;

or

<label>: BEGIN
IF (<conditions>) THEN
    -- do things
ELSEIF (<conditions>) THEN
    -- do other things
ELSE 
    -- other things
END IF;
END <label>;

which are slightly less ugly. The goal is to find a more sensible and concise way of defining if statements, so other solutions are also appreciated. Thanks for your support in advance.

Aucun commentaire:

Enregistrer un commentaire