My first stored procedure in MySQL. I hope it doesnt open a can of worms for me. I’ve already experienced the pitfalls of putting too much logic in the database (SP’s) and don’t intend on allowing history to repeat itself.
CREATE PROCEDURE CreateReportUnits(IN num INT, unit VARCHAR(20))
SQL SECURITY INVOKER
BEGIN
TRUNCATE test.report_days;
SET @i = 0;
WHILE @i < num DO
SET @i = @i + 1;
SET @query = CONCAT("INSERT INTO test.report_days ( report_day_timestamp ) VALUES ( DATE_SUB(CURDATE(),INTERVAL ",@i," ",unit,") );");
PREPARE statement FROM @query;
EXECUTE statement;
END WHILE;
END
# To invoke use:
CALL CreateReportUnits(6 'MONTH');
The invocation will create a record for the last 6 months based on today’s date to use in reports.