Error when creating Index for table Mysql - mysql

I'm working on create index for table with mysql.
I've 2 tables:
1. account
2. x_activity (x is the account_id related to "account" table, EX: 1_activity, 2_activity).
So i've created an "Index" for activity table:
Here are my code:
DROP PROCEDURE if exists update_index_for_table;
DELIMITER $$
CREATE PROCEDURE update_index_for_table()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE accountid INT;
--
-- GET ALL ACCOUNT ID
--
DECLARE accountids CURSOR FOR SELECT account_id FROM account;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
--
-- LOOP
--
OPEN accountids;
read_loop: LOOP
FETCH accountids INTO accountid;
IF done THEN
LEAVE read_loop;
END IF;
--
-- INDEX FOR ACTIVITY
--
SET #update_activity_table_1 = CONCAT("
IF (
SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS
WHERE `TABLE_SCHEMA` = DATABASE() AND TABLE_NAME='",accountid,"_activity' AND
INDEX_NAME='IDX_",accountid,"_ACTIVITY_ACTIVITY_ID'
) != 1
THEN
ALTER TABLE ",accountid,"_activity
ADD KEY `IDX_",accountid,"_ACTIVITY_ACTIVITY_ID` (`activity_id`);
END IF;
");
PREPARE stmt from #update_activity_table_1;
EXECUTE stmt;
END LOOP;
CLOSE accountids;
END$$
DELIMITER ;
CALL update_index_for_table();
But then, for some php/mysql version (i think), its cause an error like this:
#1064 - 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 'IF (
SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS
WHERE `TABLE_SCHEM' at line 1
I've tested this code and its work fine:
SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS
WHERE `TABLE_SCHEMA` = DATABASE() AND TABLE_NAME='",accountid,"_activity' AND
INDEX_NAME='IDX_",accountid,"_ACTIVITY_ACTIVITY_ID'
Here are my php/sql version:
phpmyadmin: 4.8.5, php version: 7.2.7, mysql: 5.6.45
Please help, thanks.

There are a couple of constraints on what you are trying to do here 1) you cannot run an if statement outwith a stored program 2)if you pass a query to dynamic sql and the query does not find anything the continue handler will be invoked and the loop will terminate (unexpectedly) early. The approach then is to split the functionality to first check existence by amending the 'find' to insert a value to a user defined variable and at the same time ensure the handler is not hijacked by a not found by including a look up on a table which will definitely contain something (in this case information.schema_tables.
So given
DROP PROCEDURE if exists p;
DELIMITER $$
CREATE PROCEDURE p()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE accountid INT;
--
-- GET ALL ACCOUNT ID
--
DECLARE accountids CURSOR FOR SELECT account_id FROM account;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
--
-- LOOP
--
OPEN accountids;
read_loop: LOOP
FETCH accountids INTO accountid;
select accountid;
IF done = true THEN
select accountid, 'leaving';
LEAVE read_loop;
END IF;
--
-- INDEX FOR ACTIVITY
--
SET #test := 0;
SET #update_activity_table_1 :=
(concat('SELECT case when index_name is null then 1 else 0 end into #test FROM
information_schema.tables it
left join INFORMATION_SCHEMA.STATISTICS iss ',
' on iss.table_schema = it.table_schema and iss.table_name = it.table_name and ',
'INDEX_NAME=',char(39),'IDX_',accountid,'_ACTIVITY_ACTIVITY_ID',char(39),
' WHERE it.TABLE_SCHEMA = ', char(39),'test',char(39), ' AND ',
'it.TABLE_NAME=',char(39),accountid,'_activity', char(39),
';'
)
)
;
select #update_activity_table_1;
PREPARE stmt from #update_activity_table_1;
EXECUTE stmt;
deallocate prepare stmt;
if #test = 1 then
select 'Did not find index for ' , accountid, '_extract';
else
select 'Found index for ' , accountid, '_extract';
end if;
END LOOP;
CLOSE accountids;
END $$
DELIMITER ;
call p();
I'll leave you to build the alter statement and insert into the if statement.
given
use test;
drop table if exists account,`1_activity`,`2_activity`,`64_activity`;
create table account (account_id int);
create table `1_activity`(id int);
create table `2_activity`(id int);
create table `64_activity`(id int);
insert into account values (1),(2),(64);
MariaDB [test]> call p();
+-----------+
| accountid |
+-----------+
| 1 |
+-----------+
1 row in set (0.00 sec)
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| #update_activity_table_1 |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| SELECT case when index_name is null then 1 else 0 end into #test FROM
information_schema.tables it
left join INFORMATION_SCHEMA.STATISTICS iss on iss.table_schema = it.table_schema and iss.table_name = it.table_name and INDEX_NAME='IDX_1_ACTIVITY_ACTIVITY_ID' WHERE it.TABLE_SCHEMA = 'test' AND it.TABLE_NAME='1_activity'; |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
+-------------------------+-----------+----------+
| Did not find index for | accountid | _extract |
+-------------------------+-----------+----------+
| Did not find index for | 1 | _extract |
+-------------------------+-----------+----------+
1 row in set (0.28 sec)
+-----------+
| accountid |
+-----------+
| 2 |
+-----------+
1 row in set (0.30 sec)
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| #update_activity_table_1 |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| SELECT case when index_name is null then 1 else 0 end into #test FROM
information_schema.tables it
left join INFORMATION_SCHEMA.STATISTICS iss on iss.table_schema = it.table_schema and iss.table_name = it.table_name and INDEX_NAME='IDX_2_ACTIVITY_ACTIVITY_ID' WHERE it.TABLE_SCHEMA = 'test' AND it.TABLE_NAME='2_activity'; |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.30 sec)
+-------------------------+-----------+----------+
| Did not find index for | accountid | _extract |
+-------------------------+-----------+----------+
| Did not find index for | 2 | _extract |
+-------------------------+-----------+----------+
1 row in set (0.47 sec)
+-----------+
| accountid |
+-----------+
| 64 |
+-----------+
1 row in set (0.49 sec)
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| #update_activity_table_1 |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| SELECT case when index_name is null then 1 else 0 end into #test FROM
information_schema.tables it
left join INFORMATION_SCHEMA.STATISTICS iss on iss.table_schema = it.table_schema and iss.table_name = it.table_name and INDEX_NAME='IDX_64_ACTIVITY_ACTIVITY_ID' WHERE it.TABLE_SCHEMA = 'test' AND it.TABLE_NAME='64_activity'; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.50 sec)
+-------------------------+-----------+----------+
| Did not find index for | accountid | _extract |
+-------------------------+-----------+----------+
| Did not find index for | 64 | _extract |
+-------------------------+-----------+----------+
1 row in set (0.66 sec)
+-----------+
| accountid |
+-----------+
| 64 |
+-----------+
1 row in set (0.67 sec)
+-----------+---------+
| accountid | leaving |
+-----------+---------+
| 64 | leaving |
+-----------+---------+
1 row in set (0.67 sec)
Query OK, 0 rows affected (0.69 sec)

Firstly, i believe accound_id and activity_id are both your unique keys, but what am not sure if you are auto incrementing it, check to see if the auto increment is check.

Related

mysql stored procedure issue: insert runs first and always whatever If condition I put

Need quick help, in below SQL insert is fired first then other select queries are fired. insert statement is executed whatever If condition I put.
I am testing this in phpMyAdmin.
I tried to also convert the insert statement in to separate stored procedure but then also result is same.
Thanks in Advance..
DELIMITER $$
DROP PROCEDURE IF EXISTS get_top$$
CREATE PROCEDURE get_top(
IN tolerance INT,
IN cred INT,
IN cgreen INT,
IN cblue INT,
IN userID INT,
IN mapID BIGINT
)
BEGIN
DECLARE topList VARCHAR(255) DEFAULT NULL;
DECLARE top1 VARCHAR(255) DEFAULT NULL;
DECLARE top2 VARCHAR(255) DEFAULT NULL;
DECLARE top3 VARCHAR(255) DEFAULT NULL;
DECLARE get_result VARCHAR(255) DEFAULT NULL;
DECLARE dev_notes VARCHAR(255) DEFAULT NULL;
SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';
SELECT CONCAT(top_1, ';', top_2, ';', top_3) INTO topList
FROM Tops
WHERE red = cred AND green = cgreen AND blue = cblue
ORDER BY top_ID asc
LIMIT 0 , 1 ;
SELECT topList,cred,cgreen,cblue;
IF topList IS NULL THEN BEGIN
SELECT top_1, top_2, top_3
INTO top1, top2, top3
FROM Tops
WHERE top_1>0
LIMIT 0 , 1 ;
SELECT "in IF",top1,CHAR_LENGTH(top1);
IF (top1 IS NULL) THEN
SET get_result:= 'None';
ELSE
SET get_result:= 'Nearest';
END IF;
SET topList=top1+ ','+ top2+ ','+ top3;
SET dev_notes='result:'+get_result+' mapID:'+mapID+' User ID:'+userID+' date/time:'+NOW();
SELECT topList,get_result;
INSERT INTO Tops (red,green,blue,top_1,top_2,top_3,notes) VALUES (cred,cgreen,cblue,top1,top2,top3,dev_notes);
END;
ELSE BEGIN
SET get_result:= 'Exact';
SELECT "in else",topList,get_result,dev_notes;
END; END IF;
IF CHAR_LENGTH(mapID)>0 THEN
UPDATE Map SET toponym=toponymList, toponym_conf=get_result WHERE map_ID=mapID;
END IF;
END$$
DELIMITER ;
I have amended you code to write debug messages to a table so that I can illustrate what is happening.
DELIMITER $$
DROP PROCEDURE IF EXISTS get_top$$
CREATE PROCEDURE get_top(
IN tolerance INT,
IN cred INT,
IN cgreen INT,
IN cblue INT,
IN userID INT,
IN mapID BIGINT
)
BEGIN
DECLARE topList VARCHAR(255) DEFAULT NULL;
declare topsid int;
DECLARE top1 VARCHAR(255) DEFAULT null;
DECLARE top2 VARCHAR(255) DEFAULT null;
DECLARE top3 VARCHAR(255) DEFAULT null;
DECLARE get_result VARCHAR(255) DEFAULT NULL;
DECLARE dev_notes VARCHAR(255) DEFAULT NULL;
SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';
SELECT top_id,CONCAT(top_1, ';', top_2, ';', top_3) INTO topsid,topList
FROM Tops
WHERE red = cred AND green = cgreen AND blue = cblue
ORDER BY top_ID asc
LIMIT 0 , 1 ;
insert into debug_table (msg) values (concat('Start topsid:', coalesce(topsid,'not found'),' toplist:',coalesce(topList,'null'),' cred:',cred,' cgreen:',cgreen,' cblue:',cblue));
IF topList IS NULL THEN
BEGIN
SELECT top_1, top_2, top_3
INTO top1, top2, top3
FROM Tops
WHERE top_1>0
LIMIT 0 , 1 ;
insert into debug_table (msg) values (concat("in IF",' top1:',coalesce(top1,'null'),' len top1:',if(top1 is not null,CHAR_LENGTH(top1),0)));
IF (top1 IS NULL) THEN
SET get_result:= 'None';
ELSE
SET get_result:= 'Nearest';
END IF;
SET topList=top1+ ','+ top2+ ','+ top3;
#SET dev_notes='result:'+get_result+' mapID:'+mapID+' User ID:'+userID+' date/time:'+NOW();
SET dev_notes=CONCAT('result:',get_result,' mapID:',mapID,' User ID:',userID,' date/time:',NOW());
insert into debug_table (msg) values (concat('about to insert toplist:',coalesce(topList,'null'),' get_result:',get_result,' dev_notes:',DEV_NOTES));
INSERT INTO Tops (red,green,blue,top_1,top_2,top_3,notes) VALUES (cred,cgreen,cblue,top1,top2,top3,dev_notes);
END;
ELSE BEGIN
SET get_result:= 'Exact';
insert into debug_table (msg) values (concat(' in else toplist:',coalesce(topList,'null'),' get_result:',get_result,' dev_notes:',DEV_NOTES));
END;
END IF;
#SELECT CHAR_LENGTH(MAPID);
#IF CHAR_LENGTH(mapID)>0 THEN
# UPDATE Map SET toponym=toponymList, toponym_conf=get_result WHERE map_ID=mapID;
#END IF;
END$$
DELIMITER ;
So if tops looks something like this
DROP TABLE IF EXISTS TOPS;
CREATE TABLE TOPS(TOP_ID INT AUTO_INCREMENT PRIMARY KEY,
red INT,green INT,blue INT,top_1 varchar(4),top_2 varchar(4),top_3 varchar(4),notes VARCHAR(100));
And I do this
ariaDB [sandbox]> TRUNCATE TABLE TOPS;
Query OK, 0 rows affected (0.16 sec)
MariaDB [sandbox]> truncate table debug_table;
Query OK, 0 rows affected (0.24 sec)
MariaDB [sandbox]> CALL GET_TOP(1,1,1,1,'1','1');
Query OK, 1 row affected (0.17 sec)
MariaDB [sandbox]> select * from tops;
+--------+------+-------+------+-------+-------+-------+-------------------------------------------------------------+
| TOP_ID | red | green | blue | top_1 | top_2 | top_3 | notes |
+--------+------+-------+------+-------+-------+-------+-------------------------------------------------------------+
| 1 | 1 | 1 | 1 | NULL | NULL | NULL | result:None mapID:1 User ID:1 date/time:2017-07-20 09:45:00 |
+--------+------+-------+------+-------+-------+-------+-------------------------------------------------------------+
1 row in set (0.00 sec)
MariaDB [sandbox]> CALL GET_TOP(1,1,1,1,'1','1');
Query OK, 1 row affected (0.10 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM debug_table;
+----+--------------------------------------------------------------------------------------------------------------------+
| id | msg |
+----+--------------------------------------------------------------------------------------------------------------------+
| 1 | Start topsid:not found toplist:null cred:1 cgreen:1 cblue:1 |
| 2 | in IF top1:null len top1:0 |
| 3 | about to insert toplist:null get_result:None dev_notes:result:None mapID:1 User ID:1 date/time:2017-07-20 09:45:00 |
| 4 | Start topsid:1 toplist:null cred:1 cgreen:1 cblue:1 |
| 5 | in IF top1:null len top1:0 |
| 6 | about to insert toplist:null get_result:None dev_notes:result:None mapID:1 User ID:1 date/time:2017-07-20 09:45:00 |
+----+--------------------------------------------------------------------------------------------------------------------+
6 rows in set (0.00 sec)
I would expect on the first call that no record will be found in tops and topslist will be null and this is proved by the first three records in the debug_table. On the second call a record is found in tops but since top_1,top_2 and top_3 are null then topslist is again null. The select in the if "fails" because there are no tops_1 records with a value > 0 so another record is inserted with null values to tops this is traceable in the debug_table records 4 -6. BTW checking a varchar field for a value > 0 is not a good idea.

How to split a result from select column in mySQL to a mutiple columns

I have column in MYSQL database would like to extract that column data and split it into multiple columns Here is a sample of data that I would like to split
```
{"1744":"1","1745":"1","1747":"1","1748":"1","1749":"1","1750":"1"}
{"1759":"1"}
{"47":"1","48":"Ehebr","49":"1479977045596.jpg"}
```
I would like to split that into two columns like so with the first data:
as you notice this data come in different lengths and would like to be able to split any length of data, had a look here [How to split a resulting column in multiple columns
but I don't think that is what i want the result I got there was like so would also like to trim all the other braces and quotes on the data. here is my code so far
```
SELECT combined,SUBSTRING_INDEX( combined , ':', 1 ) AS a,
SUBSTRING_INDEX(SUBSTRING_INDEX( combined , ':', 2 ),':',-1) AS b,
SUBSTRING_INDEX(SUBSTRING_INDEX( combined , ':', -2 ),':',1) AS c,
SUBSTRING_INDEX( combined , ':', -1 ) AS d
FROM tablefoo WHERE combined is not null;
```
If you can live with procedures and cursors
drop procedure if exists p;
delimiter //
CREATE DEFINER=`root`#`localhost` PROCEDURE `p`(
IN `instring` varchar(255)
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin
declare tempstring varchar(10000);
declare outstring varchar(100);
declare c1 varchar(100);
declare c2 varchar(100);
declare checkit int;
declare done int;
DECLARE CUR1 CURSOR for SELECT t.col FROM T;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
drop table if exists occursresults;
create table occursresults (col1 varchar(20), col2 varchar(20));
open CUR1;
read_loop: LOOP
FETCH CUR1 INTO tempstring;
if done then leave read_loop; end if;
set tempstring = replace(tempstring,'{','');
set tempstring = replace(tempstring,'}','');
set tempstring = replace(tempstring,'"','');
set checkit = 0;
#select tempstring;
looper: while tempstring is not null and instr(tempstring,',') > 0 do
set checkit = checkit + 1;
if checkit > 100 then #In case of infinite loop
leave looper;
end if;
set outstring = substr(tempstring,1,instr(tempstring, ',') - 1);
set tempstring = ltrim(rtrim(replace(tempstring,concat(outstring,','),'')));
set c1 = substr(outstring,1,instr(outstring, ':') - 1);
set c2 = replace(outstring,concat(c1,':'),'');
INSERT INTO OCCURSRESULTS (COL1,COL2) VALUES (c1,c2);
# select tempstring,outstring,c1,c2;
end while;
#select tempstring;
set outstring = tempstring;
set c1 = substr(outstring,1,instr(outstring, ':') - 1);
set c2 = replace(outstring,concat(c1,':'),'');
INSERT INTO OCCURSRESULTS (Col1,Col2) VALUES (c1,c2);
end loop;
close cur1;
end //
delimiter ;
MariaDB [sandbox]> select * from t;
+---------------------------------------------------------------------+
| col |
+---------------------------------------------------------------------+
| {"1744":"1","1745":"1","1747":"1","1748":"1","1749":"1","1750":"1"} |
| {"1759":"1"} |
| {"47":"1","48":"Ehebr","49":"1479977045596.jpg"} |
+---------------------------------------------------------------------+
3 rows in set (0.00 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> call p(1);
Query OK, 0 rows affected (0.65 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM OCCURSRESULTS;
+------+-------------------+
| col1 | col2 |
+------+-------------------+
| 1744 | 1 |
| 1745 | 1 |
| 1747 | 1 |
| 1748 | 1 |
| 1749 | 1 |
| 1750 | 1 |
| 1759 | 1 |
| 47 | 1 |
| 48 | Ehebr |
| 49 | 1479977045596.jpg |
+------+-------------------+
10 rows in set (0.00 sec)

MySQL - Trigger - Before Insert and using the SK (Auto Increment)

I have a simple posts table in MySQL which has a POST_ID as the SK (surrogate key).
Replies to the original post ID are stored in the same table in a PARENT_POST_ID column, but I want to perform the following logic:
BEFORE INSERT (I think ...)
IF a PARENT_POST_ID has not been defined on the INSERT, then default the row value to the newly generated POST_ID (from the auto-int sequence)
IF a PARENT_POST_ID has been defined on the INSERT, then set it to whatever has been passed.
Example
post_id | parent_post_id | date_time | message
12 12 2015-04-14 21:10 A new post (start of a thread)
13 12 2015-04-14 21:12 A reply to the post ID 12
The answer here: https://stackoverflow.com/a/11061766/1266457 looks like it might be what I need to do, although I am not sure what it's doing.
Thanks.
For before insert trigger you can not get the last inserted primary key , the other way of doing it is to get the max value from the table and increment it.
Here is a way to do it
delimiter //
create trigger posts_before_ins before insert on posts
for each row
begin
declare last_id int;
if new.parent_post_id is null then
select max(post_id) into last_id from posts ;
if last_id is null then
set new.parent_post_id = 1 ;
else
set new.parent_post_id = last_id+1 ;
end if ;
end if ;
end ;//
delimiter ;
So the trigger will check if there is no value of parent_post_id in the insert query it will get the max post_id. For the first entry it will be null so we are setting it as 1 i.e. and after that max post_id + 1 after each entry.
Here is a test case of this in mysql
mysql> select * from test ;
Empty set (0.00 sec)
mysql> delimiter //
mysql> create trigger test_is before insert on test
-> for each row
-> begin
-> declare last_id int;
-> if new.parent_id is null then
-> SELECT auto_increment into last_id
-> FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'test'
-> and TABLE_SCHEMA = 'test';
-> set new.parent_id = last_id ;
-> end if ;
-> end ;//
Query OK, 0 rows affected (0.12 sec)
mysql>
mysql> delimiter ;
mysql> insert into test (val) values ('aa');
Query OK, 1 row affected (0.10 sec)
mysql> insert into test (val) values ('bb');
Query OK, 1 row affected (0.04 sec)
mysql> select * from test ;
+---------+-----------+------+
| post_id | parent_id | val |
+---------+-----------+------+
| 1 | 1 | aa |
| 2 | 2 | bb |
+---------+-----------+------+
2 rows in set (0.00 sec)

Mysql select statement only works on first iteration in while loop, insert working fine

Why is the SELECT statement inside the WHILE loop only returning value for the first iteration ?
Both of the INSERT IGNORE and the second INSERT is working, and are inserting rows equal to amount.
If I set amount to 10, I only get the results from the first inserted row. However, the procedure will INSERT amount rows to rand_strings and rand_strings_info tables.
The Procedure:
DROP PROCEDURE if exists test_while;
DELIMITER $$
CREATE PROCEDURE test_while(amount INT, description VARCHAR(255))
BEGIN
WHILE amount > 0 DO
INSERT IGNORE INTO rand_strings(rand_string) /*WORKS EVERY ITERATION*/
SELECT generate_rand_string(); /*function to generate a random string.*/
SELECT * FROM rand_strings WHERE id = LAST_INSERT_ID(); /*ONLY WORKS FIRST TIME */
INSERT INTO rand_strings_info(id, col2, col3) /*WORKS EVERY ITERATION*/
VALUES (LAST_INSERT_ID(), now(), description);
SET amount = amount - 1;
END WHILE;
END$$
DELIMITER ;
CALL test_while(10, 'This is the description of the string…')
RESULTS:
id | rand_string
1 | jgdlkjaht
Some interfaces do not show all the results as expected, but the code runs correctly.
You can see in the following SQL Fiddle that only shows the first record in the rand_strings table when stored procedure runs, but running the same code on the MySQL command line the result is as follows:
mysql> CALL `test_while`(5, 'This is the description of the string...');
+----+------------------------------------------+
| id | rand_string |
+----+------------------------------------------+
| 1 | f4c77a3155d95ad1e818b1b06a62deec8e0b6754 |
+----+------------------------------------------+
1 row in set (0.00 sec)
+----+------------------------------------------+
| id | rand_string |
+----+------------------------------------------+
| 2 | 7cbcca49596262836f5af91643303d10b3804900 |
+----+------------------------------------------+
1 row in set (0.00 sec)
+----+------------------------------------------+
| id | rand_string |
+----+------------------------------------------+
| 3 | 2ba2c7276c0b66e3dcbb971b7f54af9bced578a4 |
+----+------------------------------------------+
1 row in set (0.00 sec)
+----+------------------------------------------+
| id | rand_string |
+----+------------------------------------------+
| 4 | d52426b19a59c515b02268347c508383873d4d73 |
+----+------------------------------------------+
1 row in set (0.00 sec)
+----+------------------------------------------+
| id | rand_string |
+----+------------------------------------------+
| 5 | fbc25c6204b609e8f4f4f8a33b534bff9a011e5f |
+----+------------------------------------------+
1 row in set (0.00 sec)
Query OK, 1 row affected (0.00 sec)
UPDATE
DELIMITER $$
CREATE PROCEDURE `test_while`(`amount` INT, `description` VARCHAR(255))
BEGIN
DECLARE `_LAST_INSERT_ID`, `_first_inserted_in_this_run` INT UNSIGNED DEFAULT NULL;
CREATE TEMPORARY TABLE IF NOT EXISTS `temp_generate_rand_string` (
`insert_id` INT UNSIGNED PRIMARY KEY,
`first_inserted_in_this_run` INT UNSIGNED
) ENGINE=MEMORY;
WHILE `amount` > 0 DO
INSERT IGNORE INTO `rand_strings`(`rand_string`) /*WORKS EVERY ITERATION*/
SELECT `generate_rand_string`(); /*function to generate a random string.*/
SET `_LAST_INSERT_ID` := LAST_INSERT_ID();
IF (`_first_inserted_in_this_run` IS NULL) THEN
SET `_first_inserted_in_this_run` := `_LAST_INSERT_ID`;
END IF;
INSERT INTO `temp_generate_rand_string` (`insert_id`, `first_inserted_in_this_run`)
VALUES
(`_LAST_INSERT_ID`, `_first_inserted_in_this_run`);
-- SELECT * FROM `rand_strings` WHERE `id` = `_LAST_INSERT_ID`; /*ONLY WORKS FIRST TIME */
INSERT INTO `rand_strings_info`(`id`, `col2`, `col3`) /*WORKS EVERY ITERATION*/
VALUES (`_LAST_INSERT_ID`, NOW(), `description`);
SET `amount` := `amount` - 1;
END WHILE;
SELECT `rs`.`id`, `rs`.`rand_string`
FROM `rand_strings` `rs`
INNER JOIN `temp_generate_rand_string` `tgrs` ON
`tgrs`.`first_inserted_in_this_run` = `_first_inserted_in_this_run` AND
`rs`.`id` = `tgrs`.`insert_id`;
DELETE
FROM `temp_generate_rand_string`
WHERE `first_inserted_in_this_run` = `_first_inserted_in_this_run`;
END$$
DELIMITER ;
SQL Fiddle demo

Launch Trigger and Routine on Insert

Im attempting to have MySQL automatically insert data into another table after insert into one. I know to do this required Triggers and potentially Routines. I have a couple I've been trying to modify to do what I wish to accomplish but I appear to be hitting a dead end due to lack of experience, so help is greatly appreciated.
The table that has data inserted (db_tou_tracking):
tou_tracking_ID ICP_ID tou_tracking_start tou_tracking_units
----------------------------------------------------------------
2 2 2013-03-01 10.77
3 2 2013-03-01 11.00
There are a couple of other columns here, that separate out by time, but I'm interested by day, rather than time.
Table data should go into compounded. So as each of the above rows are inserted, it will either create a new row if the tou_tracking_start and ICP_ID do not exist, or update the existing row.
tou_tracking_daily_ID ICP_ID tou_tracking_start tou_tracking_units
------------------------------------------------------------------------------
1 2 2013-03-01 21.77
2 2 2013-03-02 25.36
Below is my Tigger (no errors when setup on MySQL, and it does appear to call when data is attempted to be inserted):
BEGIN
DECLARE presentcount INT;
SET presentcount = (SELECT count(*) FROM db_tou_tracking_daily WHERE tou_tracking_daily_day =
(SELECT tou_tracking_start FROM db_tou_tracking WHERE ICP_ID = db_tou_tracking_daily.ICP_ID ORDER BY tou_tracking_ID DESC)
);
IF (presentcount = 0) THEN
INSERT INTO db_tou_tracking_daily (ICP_ID, tou_tracking_daily_day, tou_tracking_start)
SELECT NEW.ICP_ID, NEW.tou_tracking_start, NEW.tou_tracking_units, calculate_units(NEW.ICP_ID, NEW.tou_tracking_start);
ELSE
UPDATE db_tou_tracking_daily SET tou_tracking_daily_units = calculate_units(NEW.ICP_ID, tou_tracking_daily_day)
WHERE ICP_ID = NEW.ICP_ID AND tou_tracking_daily_day = NEW.tou_tracking_start;
END IF;
END
and then the routine it calls to calculate units.
CREATE DEFINER=`root`#`localhost` FUNCTION `calculate_units`(ICP_ID INT, tou_tracking_daily_day DATE) RETURNS float
BEGIN
DECLARE units FLOAT;
DECLARE last_time DATE;
DECLARE last_watts INT;
DECLARE this_time DATETIME;
DECLARE this_watts INT;
DECLARE loop_done INT;
DECLARE curs CURSOR FOR
SELECT tou_tracking_timestart, tou_tracking_units FROM db_tou_tracking WHERE ICP_ID = ICP_ID AND tou_tracking_start = tou_tracking_daily_day ORDER BY tou_tracking_start DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done = 1;
SET last_time = (SELECT max(tou_tracking_start) FROM db_tou_tracking WHERE ICP_ID = ICP_ID AND tou_tracking_start < tou_tracking_daily_day);
SET last_watts = (SELECT tou_tracking_units FROM db_tou_tracking WHERE ICP_ID = ICP_ID AND tou_tracking_start = last_time);
SET last_time = CAST(tou_tracking_start AS DATETIME);
SET loop_done = 0;
SET units = 0;
OPEN curs;
REPEAT
FETCH curs INTO this_time, this_watts;
IF last_watts IS NOT NULL THEN
SET units = units + (last_watts + this_watts);
END IF;
SET last_watts = this_watts;
SET last_time = this_time;
UNTIL loop_done END REPEAT;
CLOSE curs;
END
The routine throws back an error on line 3 when I try to run the SQL to setup the routine, but I can't see anything obviously wrong, but I'm not exactly sure what I'd be looking for.
Any help with this is hugely appreciated and any pointers that can be given along the way. Thanks :)
Attempting to replicate your issue, I'm going to guess the error you get is probably because you're not using a DELIMITER.
Executing a similar function creation statement I get the same error, and a syntax parse suggests it's not expecting the delimiter ;.
The one that causes an error on line 3.
CREATE DEFINER = 'root'#'localhost' FUNCTION test_func(foo INT) RETURNS FLOAT
BEGIN
DECLARE bar FLOAT;
RETURN 1;
END
Fixing it using delimiters.
DELIMITER $$
CREATE DEFINER = 'root'#'localhost' FUNCTION test_func(foo INT) RETURNS FLOAT
BEGIN
DECLARE bar FLOAT;
RETURN 1;
END$$
DELIMITER ;
If this does not fix your problem, are you able to provide a self contained function that doesn't rely on any of your existing tables, that also produces the same error so it can be tested?
create table t1 ( start date not null, units decimal(5,2) not null );
create table t2 ( start date not null, units decimal(5,2) not null );
delimiter //
create trigger trg1
after insert on t1
for each row
begin
update t2
set units = units + new.units
where start = new.start;
if ROW_COUNT() = 0 then
insert into t2
(start, units)
values (new.start, new.units);
end if;
end //
delimiter ; //
mysql> select * from t1;
Empty set (0.01 sec)
mysql> select * from t2;
Empty set (0.00 sec)
mysql> insert into t1 (start, units) values ('2014-01-01',100.02);
Query OK, 1 row affected (0.01 sec)
mysql> select * from t1;
+------------+--------+
| start | units |
+------------+--------+
| 2014-01-01 | 100.02 |
+------------+--------+
1 row in set (0.00 sec)
mysql> select * from t2;
+------------+--------+
| start | units |
+------------+--------+
| 2014-01-01 | 100.02 |
+------------+--------+
1 row in set (0.00 sec)
mysql> insert into t1 (start, units) values ('2014-01-01',200.05);
Query OK, 1 row affected (0.01 sec)
mysql> select * from t1;
+------------+--------+
| start | units |
+------------+--------+
| 2014-01-01 | 100.02 |
| 2014-01-01 | 200.05 |
+------------+--------+
2 rows in set (0.01 sec)
mysql> select * from t2;
+------------+--------+
| start | units |
+------------+--------+
| 2014-01-01 | 300.07 |
+------------+--------+
1 row in set (0.01 sec)