Inserting random data into a table in MySql - mysql

Could someone please help me? I don't know what the problem here
DROP PROCEDURE IF EXISTS insertRandom;
CREATE PROCEDURE insertRandom()
BEGIN
DECLARE mytime timestamp;
SET mytime := '2009-01-01 00:00:00'
BEGIN
test_loop : LOOP
while mytime < now()
mytime = mytime + interval '8 hours';
insert into tempdata(temp_val, datum) values((select random()*(110)-10), mytime);
END LOOP;
END;
CALL insertRandom;
SELECT * FROM `temp_table`;

You have many errors in your code
Use this Procedure instead
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `insertRandom`()
BEGIN
DECLARE mytime timestamp;
SET mytime := '2009-01-01 00:00:00';
DROP TEMPORARY TABLE IF EXISTS tempdata;
CREATE TEMPORARY TABLE tempdata (temp_val BIGINT, datum timestamp);
test_loop : LOOP
IF mytime >= now() THEN
LEAVE test_loop;
END IF;
SET mytime = TIMESTAMPADD(HOUR,8,mytime);
insert into tempdata(temp_val, datum) values((select (rand()*110)-10), mytime);
END LOOP;
END$$
DELIMITER ;
And then
call insertRandom();
SELECT * FROM tempdata;

Looks like a semicolon in the procedure body is terminating the statement. We need MySQL to see the CREATE PROCEDURE as a single statement, but MySQL is chopping the statement off, seeing a complete statement when it sees a semicolon.
The default statement delimiter in MySQL is semicolon ; character. The default delimiter can be overridden; we change with the DELIMITER statement.
Example here of temporarily modifying the statement delimiter to be two dollar sign characters $$. Within the procedure body, occurrences of the semicolon character won't terminate the statement... MySQL will keep reading until it finds two dollar sign characters. (Goes without saying that the procedure body shouldn't contain $$)
DELIMITER $$
DROP PROCEDURE IF EXISTS insertRandom $$
CREATE PROCEDURE insertRandom()
...
...
...
END$$
DELIMITER ;
CALL insertRandom();
Note that we use the DELIMITER statement to change the delimiter back to the semicolon character. I did not check the body of the procedure for other syntax errors; but some things stick out. For example, this looks wrong
mytime = mytime + interval '8 hours';
that should probably be SET statement, and the syntax is like this:
SET mytime = mytime + INTERVAL 8 HOUR;
In the SET statement, we can use the := in place of = as the assignment operator, so equivalent
SET mytime := mytime + INTERVAL 8 HOUR;
For looping withing a MySQL stored program, we can do a LOOP ... END LOOP and include a LEAVE statement, or we can use a WHILE loop, or ...
Syntax documented here:
https://dev.mysql.com/doc/refman/5.7/en/while.html
https://dev.mysql.com/doc/refman/5.7/en/loop.html

Related

How do I make this procedure generate random times (HH:MM:SS) but with the current date?

I need this procedure to generate 10M random timestamps but it has to use the current date each time it is called, how do i do this? I know that there's a CURRENT_TIMESTAMP() function, but I'm not sure how to implement it.
DELIMITER $$
CREATE PROCEDURE producer()
BEGIN
DECLARE a INT DEFAULT 0;
WHILE a < 10000000 DO
INSERT INTO CaseLog (`TIMESTAMP_IN`)
VALUES (FROM_UNIXTIME(UNIX_TIMESTAMP('2021-09-22 00:00:00')+FLOOR(RAND()*86399))
);
SET a = a+1;
END WHILE;
END$$
DELIMITER ;
Use CURRENT_DATE() to get today's date, and use that instead of the hard-coded date.
DELIMITER $$
CREATE PROCEDURE producer()
BEGIN
DECLARE today_timestamp INT;
SET today_timestamp = UNIX_TIMESTAMP(CURRENT_DATE());
DECLARE a INT DEFAULT 0;
WHILE a < 10000000 DO
INSERT INTO CaseLog (`TIMESTAMP_IN`)
VALUES (FROM_UNIXTIME(today_timestamp+FLOOR(RAND()*86400)));
SET a = a+1;
END WHILE;
END$$
DELIMITER ;
Also, you should multiply RAND() by 86400, not 86399. The result of RAND() is always less than 1.0, so you don't have to worry that it will return 86400.

End while loop missing semicolon

I created a simple stored procedure that loops through rows of one table and inserts them into another. For some reason the END WHILE loop is throwing a missing semicolon error. All the code looked right to me, and all the delimiters were set up right. I just can't figure out why it would be throwing these errors, googling this problem only pointed me to improperly used delimiter answers, but nothing more. Any help would be nice!
USE test;
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO `test_2` (sku, qty) VALUES(sku, qty) FROM `test_dropship_upload` LIMIT i,1;
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
When I am stuck with a problem in a large block of code and can't find where the problem is, I usually split my code in smaller chunks and test them one at a time:
Test 1:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE testLoop()
BEGIN
END $$
DELIMITER ;
No errors: procedure declaration and use of delimiters is OK.
Test 2:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
END $$
DELIMITER ;
No errors: the declaration of variables within the procedure is OK.
Test 3:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
END $$
DELIMITER ;
No errors: the SELECT query and the variable assignment are OK.
Test 4:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
No errors: the WHILE loop is OK.
Test 5:
The only untested part is now the INSERT query:
INSERT INTO `test_2` (sku, qty) VALUES(sku, qty) FROM `test_dropship_upload` LIMIT i,1;
Looking a the documentation for INSERT and INSERT ... SELECT, we can see that your query is not valid: it is apparently missing a SELECT part and shouldn't have a VALUES part if you want to insert values from another table:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO `test_2` (sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT i, 1;
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
The procedure creation now completes without errors.
Test 6:
However, you will get a syntax error on the SELECT query when executing the procedure: MySQL doesn't accept using LIMIT with a variable.
To make it work, you need to use a prepared statement.
PREPARE stmt FROM "INSERT INTO `test_2` (sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT ?, 1";
EXECUTE stmt using #i;
DEALLOCATE PREPARE stmt;
It is also not allowed to used local variables in prepared statements:
Because local variables are in scope only during stored program
execution, references to them are not permitted in prepared statements
created within a stored program. Prepared statement scope is the
current session, not the stored program, so the statement could be
executed after the program ends, at which point the variables would no
longer be in scope. For example, SELECT ... INTO local_var cannot be
used as a prepared statement. This restriction also applies to stored
procedure and function parameters.
To circumvent this problem, use a session variable #i instead of your local variable i:
Final version of the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET #i=0;
WHILE #i<n DO
PREPARE stmt FROM "INSERT INTO `test_2`(sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT ?, 1";
EXECUTE stmt USING #i;
DEALLOCATE PREPARE stmt;
SET #i = #i + 1;
END WHILE;
END $$
DELIMITER ;
You can apply the same method to debug many complex programming problems: start with a simple version of your code, test it. If it works test again with a more code, if not locate and fix the errors before continuing.

My sql trigger, syntax error

I want to update two columns after current row update by trigger.
endtime and starttime are datetime type. duration is integer and it will represent num of seconds. Sequel Pro tell me "[ERROR in query 1] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
Execution stopped!"
CREATE TRIGGER `end_time_update` AFTER UPDATE ON `mytable`
FOR EACH ROW
BEGIN
UPDATE mytable
set endtime = now(), duration = TIMESTAMPDIFF(SECOND, starttime, endtime)
where id = new.id;
END;
You need to change the delimiter. Otherwise the DB will terminate the definition of the trigger at the first ;
delimiter |
CREATE TRIGGER `end_time_update` BEFORE UPDATE ON `mytable`
FOR EACH ROW
BEGIN
if NEW.some_col <> OLD.some_col
then
set NEW.endtime = now();
set NEW.duration = TIMESTAMPDIFF(SECOND, NEW.starttime, NEW.endtime);
end if;
END
|
delimiter ;
You can't put an update on the same table in the trigger. That would create an endless loop. But you can use NEWto refer to the current record to modify it.
You should set your delimiter so that the semi-colons inside the trigger won't be interpreted as the end of the trigger:
-- Set the delimiter
DELIMITER $$
CREATE TRIGGER `end_time_update` AFTER UPDATE ON `mytable`
FOR EACH ROW
BEGIN
UPDATE mytable
set endtime = now(), duration = TIMESTAMPDIFF(SECOND, starttime, endtime)
where id = new.id;
END;
$$
-- Reset the delimiter
DELIMITER ;

MYSQL stored procedure if else dayname

I need to Write a stored procedure to find out the joining date of teachers and if it is a Monday it should display Monday else it should display Weekday. I am very new in stored procedure how i can display 'weekday?
I have prepared a code but am geting error.(dat_teacher_doj is in date datatype)
Delimiter //
CREATE PROCEDURE check_date(IN doj date)
BEGIN
select dayname(dat_teacher_doj)as day from tbl_teachers where dat_teacher_doj=doj;
IF day!='Monday' THEN
SET day='Weekday';
END IF
END //
Delimiter ;
AM GETTING ERROR: UNKNWN SYSTEM VARIABLE 'day'
You first need to DECLARE your variable. Then use SELECT ... INTO after you have declared your variable.
DELIMITER //
CREATE PROCEDURE check_date (IN teacher_id VARCHAR(100))
BEGIN
DECLARE day VARCHAR(100);
SELECT dayname(dat_teacher_doj) INTO day FROM tbl_teachers WHERE id = teacher_id;
SELECT CASE WHEN day != 'Monday' THEN 'Weekday' ELSE day END;
END;
//
DELIMITER ;
When you call your procedure, you need to put quotes around your input date.
call check_date('1982-01-11');

Getting errors when trying to create a PROCEDURE in mysql

I am trying to create a mysql stored procedure, but I get this error:
Script line: 2 Failed to CREATE PROCEDURE proc_test_bideep
The stored procedure code is:
DELIMITER $$
DROP PROCEDURE IF EXISTS `commun`.`insert_categorie` $$
CREATE PROCEDURE `commun`.`insert_categorie` (id_mere INT,
lib_categ VARCHAR(50),
id_categ_sup INT ,
categ_authInstantBuy INT)
BEGIN
SET #bg_mere := (SELECT categ_bg FROM categ_basic WHERE categ_id = id_mere);
#bg_mere+2,categ_level_bideep,categ_statut,categ_adult,categ_authSmallBid,categ_authBid,categ_authInstantBuy);
SELECT '1' AS code_retour; END IF;
ecetera.........
END $$
DELIMITER ;
a) You need to DECLARE any variables on the first lines of the procedure, including their datatype:
DECLARE bg_mere INT;
b) To fetch a value from the database into a variable, you use SELECT ... INTO syntax:
SELECT categ_bg INTO bg_mere FROM categ_basic WHERE categ_basic.categ_id = id_mere;
c) You have an END IF without the corresponding IF.
d) The closing END needs a semicolon (not BEGIN though), only then do you need a delimiter to finish the entire statement, and finally you should reset the delimiter back to normal:
BEGIN
# body of the stored procedure goes here
END;
$$
DELIMITER ;
Your parameters are missing the keyword IN such as: ...(IN id_mere INT, IN lib_categ ...). Also, you need to configure your OUT variable for #bg_mere in the initial parameter list such as (IN xxx, ..., OUT bg_mere VARCHAR/INT/WHATEVER).