Functions and procedures in mysql

30 Views Asked by At

[enter image description here](https://i.stack.imgur.com/ffuLC.png)

I have been trying to create this function for past 2 days now, could anyone help me figure this one out?

CREATE DEFINER=`root`@`localhost` PROCEDURE `aggressorPopulator`(
  IN num_traducers INT,
)
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE tid VARCHAR(255);

   WHILE i <= num_traducers DO
    SET tid = CONCAT('TA-', FLOOR(RAND() * 5) + 1, '-', FLOOR(RAND() * 100) + 1);
    INSERT INTO traducer (TID, TType, TLOC_X, TLoc_Y, TValue, TLethal, TStatus, TDurable)
    VALUES (
      tid,
      IF(RAND() < 0.5, 'Medium', 'Heavy'),
      ROUND(RAND() * 200),
      ROUND(RAND() * 200),
      IF(RAND() < 0.5, 10, 25),
      IF(RAND() < 0.5, 100, 300),
      IF(RAND() < 0.5, 'Available', 'Not Available'),
      ROUND(IF(RAND() < 0.5, RAND() * 0.05, RAND() * 0.1) * IF(RAND() < 0.5, 100, 300))
    );
    SET i = i + 1;
  END WHILE;
1

There are 1 best solutions below

0
SelVazi On

Your process nearly works; the first thing to do is remove the comma from the argument. Second, the final END is absent.

CREATE PROCEDURE aggressorPopulator(
  IN num_traducers INT
)
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE tid VARCHAR(255);

   WHILE i <= num_traducers DO
    SET tid = CONCAT('TA-', FLOOR(RAND() * 5) + 1, '-', FLOOR(RAND() * 100) + 1);
    INSERT INTO traducer (TID, TType, TLOC_X, TLoc_Y, TValue, TLethal, TStatus, TDurable)
    VALUES (
      tid,
      IF(RAND() < 0.5, 'Medium', 'Heavy'),
      ROUND(RAND() * 200),
      ROUND(RAND() * 200),
      IF(RAND() < 0.5, 10, 25),
      IF(RAND() < 0.5, 100, 300),
      IF(RAND() < 0.5, 'Available', 'Not Available'),
      ROUND(IF(RAND() < 0.5, RAND() * 0.05, RAND() * 0.1) * IF(RAND() < 0.5, 100, 300))
    );
    SET i = i + 1;
  END WHILE;
END;

Demo here