5
\$\begingroup\$

Make a procedure called paintletter, it receives two parameters, a letter and a number. it will have to paint on the screen lines with the specified letters starting with a letter and ending with as many letters as the parameter says (USE BUCLES).

My exercise works but can it be improved in any way?
USE almacen;
 
DELIMITER $$
DROP PROCEDURE IF EXISTS paintletter$$
CREATE PROCEDURE paintletter(IN letter CHAR(1),IN num INT)
BEGIN
    DECLARE AUX INT DEFAULT 0;
    DECLARE LETR VARCHAR(20) DEFAULT "";
    WHILE (num > AUX) DO
        SELECT CONCAT(LETR,letter);
        SET LETR = concat(LETR,letter);
        SET AUX = AUX + 1;
    END WHILE;
END $$
DELIMITER ;

For example : paintletter("B",4)

B 

BB 

BBB 

BBBB 

here is a link to how it works : https://www.db-fiddle.com/f/3PnzHErrf2fZFGZY67K12X/97

\$\endgroup\$
1
  • \$\begingroup\$ See also the REPEAT() function. \$\endgroup\$
    – Rick James
    Jul 14, 2022 at 3:54

1 Answer 1

2
\$\begingroup\$

Your procedure works, but it can be improved for clarity, efficiency, and better coding practices. Here are some suggestions:

Use meaningful variable names. Avoid unnecessary SELECT statements. Handle potential edge cases (e.g., if num is less than or equal to 0). Optimize string concatenation inside the loop.

Here is the improved version of your procedure:

USE almacen;
DELIMITER $$
DROP PROCEDURE IF EXISTS paintletter$$
CREATE PROCEDURE paintletter(IN p_letter CHAR(1), IN p_num INT)
BEGIN
    DECLARE v_counter INT DEFAULT 0;
    DECLARE v_output VARCHAR(255) DEFAULT '';

    -- Edge case handling: If the number is less than or equal to 0, exit the procedure
    IF p_num <= 0 THEN
        SELECT 'The number must be greater than 0';
        LEAVE;
    END IF;

    -- Loop to build the string and print each line
    WHILE v_counter < p_num DO
        SET v_output = CONCAT(v_output, p_letter);
        SELECT v_output;
        SET v_counter = v_counter + 1;
    END WHILE;
END $$
DELIMITER ;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.