Related
I have a stored procedure to update some rows in MySQL. But when I call the stored procedure, it affects more than actual rows.
Here is my stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `SP_INSERT_DATA`(
IN `incoming_data` TEXT,
IN `value_array` TEXT,
IN `serial_number` VARCHAR(50),
IN `data_timestamp` VARCHAR(50),
OUT `result_id` INT,
OUT `result_message` VARCHAR(500)
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE i INT;
DECLARE value_iteration VARCHAR(50);
DECLARE lcl_data_type_id INT;
DECLARE arr_data_type_name VARCHAR(50);
DECLARE affected_data_row_count INT;
DECLARE cstmr_id INT;
DECLARE exit handler FOR 40001
BEGIN
GET DIAGNOSTICS CONDITION 1
#p1 = MYSQL_ERRNO, #p2 = MESSAGE_TEXT;
SET result_id = -2;
SET result_message = CONCAT('RETURNED ERROR NO : ', #p1 , '\r\nMESSAGE TEXT : ',#p2);
ROLLBACK;
END;
DECLARE exit handler for sqlexception
BEGIN
GET DIAGNOSTICS CONDITION 1
#p1 = MYSQL_ERRNO, #p2 = MESSAGE_TEXT;
SET result_id = -999;
SET result_message = CONCAT('RETURNED ERROR NO : ', #p1 , '\r\nMESSAGE TEXT : ',#p2);
ROLLBACK;
END;
START TRANSACTION;
SET i = 1;
SET affected_data_row_count = 0;
SET cstmr_id = 0;
SET result_id = 0;
SET result_message = 'Success';
SELECT id INTO cstmr_id FROM templaricustomers WHERE templaricustomers.customer_serial_number = serial_number LIMIT 1;
IF(cstmr_id <> 0) THEN
WHILE (LOCATE(',', value_array) > 0)
DO
SET arr_data_type_name = SUBSTRING_INDEX(value_array,',',i);
SET value_array = SUBSTRING(value_array, LOCATE(',',value_array) + 1);
SELECT JSON_EXTRACT(incoming_data, arr_data_type_name) INTO value_iteration;
SET arr_data_type_name := SUBSTRING_INDEX(arr_data_type_name, ".", -1);
IF (SELECT COUNT(id) FROM datatypes WHERE datatypes.data_name = arr_data_type_name) > 0 THEN
SELECT id INTO lcl_data_type_id FROM datatypes WHERE datatypes.data_name = arr_data_type_name LIMIT 1;
ELSE
INSERT INTO datatypes (datatypes.data_name,datatypes.description ,datatypes.inserted_date) VALUES(arr_data_type_name,arr_data_type_name,NOW());
SELECT id INTO lcl_data_type_id FROM datatypes WHERE datatypes.data_name = arr_data_type_name LIMIT 1;
END IF;
IF (SELECT COUNT(id) FROM mqttpacket WHERE mqttpacket.data_type_id = lcl_data_type_id AND mqttpacket.customer_id = cstmr_id) > 0 THEN
UPDATE mqttpacket SET mqttpacket.data_value = value_iteration , mqttpacket.inserted_time = data_timestamp WHERE mqttpacket.data_type_id = lcl_data_type_id AND mqttpacket.customer_id = cstmr_id;
ELSE
INSERT INTO mqttpacket (mqttpacket.data_type_id,mqttpacket.customer_id,mqttpacket.data_value,mqttpacket.inserted_time) VALUES(lcl_data_type_id,cstmr_id,value_iteration,data_timestamp);
END IF;
SET affected_data_row_count = affected_data_row_count +1;
END WHILE;
SET result_id = 0;
SET result_message = CONCAT('Query performed successfully. Effected rows : ',CAST(affected_data_row_count AS CHAR));
ELSE
SET result_id = -1;
SET result_message = 'Customer Serial Number not found.';
END IF;
COMMIT;
END
Here is how I call it:
CALL `SP_INSERT_DATA`('{"subcooling":-40,"B1":113,"B2":206,"B3":471,"B4":226,"B5":8,"B6":380,"B7":210,"B8":187,"Discharge":135,"Suction":120,"High_Pressure":90,"Low_Pressure":90,"Evaporation":73,"Condensation":73,"MAX_CMP_SPEED":1100,"Thermal_Limit":748,"SH":46,"EEV_pct":0,"COP":0,"DSH":60,"WaterFlux":8,"FanPower":1,"DeltaTtoStart":0,"DeltaPtoStart":60,"CMP_ROTOR_RPS":0,"SET_CH_FLASH":120,"SET_HP_FLASH":350,"SET_DHW_FLASH":470,"Defrosting":0,"B8_AVERAGE":63,"SET_PLANT":0,"SET_CH_BMS":160,"SET_HP_BMS":200,"SET_DHW_BMS":480,"SET_ACTIVE":200,"SET_DSH":250,"EEV_INJ_pct":0,"LPT":0,"HPT":0,"PLANT_MODE_MANUAL":0,"DHW_MODE_MANUAL":0,"WATER_FLOW":8,"DISCHARGE_TMP":135,"INVERTER_TMP":8,"ENVELOP_ZONE":1,"EEV_A_STEPS":0,"EBM_POWER":1,"EBM_MAX_POWER":106,"COMP_pct_FINAL":0,"TOTAL_POWER_ABSORBED":10,"POWER_OUT_KW":0,"COOLINGCAPACITY":0}' , '$.subcooling,$.B1,$.B2,$.B3,$.B4,$.B5,$.B6,$.B7,$.B8,$.Discharge,$.Suction,$.High_Pressure,$.Low_Pressure,$.Evaporation,$.Condensation,$.MAX_CMP_SPEED,$.Thermal_Limit,$.SH,$.EEV_pct,$.COP,$.DSH,$.WaterFlux,$.FanPower,$.DeltaTtoStart,$.DeltaPtoStart,$.CMP_ROTOR_RPS,$.SET_CH_FLASH,$.SET_HP_FLASH,$.SET_DHW_FLASH,$.Defrosting,$.B8_AVERAGE,$.SET_PLANT,$.SET_CH_BMS,$.SET_HP_BMS,$.SET_DHW_BMS,$.SET_ACTIVE,$.SET_DSH,$.EEV_INJ_pct,$.LPT,$.HPT,$.PLANT_MODE_MANUAL,$.DHW_MODE_MANUAL,$.WATER_FLOW,$.DISCHARGE_TMP,$.INVERTER_TMP,$.ENVELOP_ZONE,$.EEV_A_STEPS,$.EBM_POWER,$.EBM_MAX_POWER,$.COMP_pct_FINAL,$.TOTAL_POWER_ABSORBED,$.POWER_OUT_KW,$.COOLINGCAPACITY,', '123456', '2021-02-24 10:43:00.00' ,#result_id, #result_message);
The table mqttpacket is a system versioned table. Here are the table creation queries.
CREATE TABLE test_database.MQTTPacket(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
data_type_id INT NOT NULL,
customer_id INT NOT NULL,
data_value INT NULL,
row_start TIMESTAMP(6) GENERATED ALWAYS AS ROW START INVISIBLE,
row_end TIMESTAMP(6) GENERATED ALWAYS AS ROW END INVISIBLE,
inserted_time TIMESTAMP(6) NULL DEFAULT NULL,
PERIOD FOR SYSTEM_TIME(row_start,row_end),
FOREIGN KEY (data_type_id) REFERENCES test_database.DataTypes(id),
FOREIGN KEY (customer_id) REFERENCES test_database.templaricustomers(id)
)WITH SYSTEM VERSIONING;
CREATE TABLE `datatypes` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`data_name` VARCHAR(50) NOT NULL COLLATE 'latin1_general_ci',
`inserted_date` DATE NULL DEFAULT NULL,
`description` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`device_id` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `device_id` (`device_id`) USING BTREE,
CONSTRAINT `datatypes_ibfk_1` FOREIGN KEY (`device_id`) REFERENCES `test_database`.`devices` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT
)
CREATE TABLE `templaricustomers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`customer_serial_number` VARCHAR(50) NOT NULL COLLATE 'latin1_general_ci',
`customer_name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`inserted_date` TIMESTAMP(6) NOT NULL DEFAULT current_timestamp(6),
PRIMARY KEY (`id`) USING BTREE
)
So, when I first call the stored procedure, my result_message variable returns "Query performed successfully. Effected rows : 53" however MySql says
Affected rows: 107 Found rows: 0 Warnings: 0 Duration for 1 query: 0.015 sec.
In the second call of the SP, it says
Affected rows: 160 Found rows: 0 Warnings: 0 Duration for 1 query: 0.031 sec.
Thankful for any help in advance.
Am trying to create a stored procedure that will notify me if a username or email already exists in the table.
Here is the structure of my table
CREATE TABLE IF NOT EXISTS `user` (
`user_id` smallint(5) unsigned NOT NULL,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`email` varchar(60) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(128) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`date_joined` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_category_id` tinyint(3) unsigned NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
and here is the code for the stored procedure
DELIMITER $$
CREATE PROCEDURE `sp_create_account`( username_param VARCHAR(40), email_param VARCHAR(60), pass VARCHAR(30), category_id TINYINT )
BEGIN
DECLARE salt VARCHAR(60);
DECLARE username_var VARCHAR(40);
DECLARE email_var VARCHAR(60);
SELECT username_var INTO username_var FROM user WHERE username = username_param;
SELECT email_var INTO email_var FROM user WHERE email = email_param;
IF username_var = username_param THEN
SELECT 'username' AS message;
ELSEIF email_var = email_param THEN
SELECT 'email' AS message;
ELSE
SET salt = '#4$^7EC%?';
SET salt = CONCAT( username_param, salt );
INSERT INTO user VALUES
( DEFAULT, username_param, email_param, AES_ENCRYPT( pass, salt ), DEFAULT, DEFAULT, category_id );
SELECT 'created' AS message;
END IF;
END$$
DELIMITER ;
Two problems:
Problem 1:
Everything works fine when inserting an unique entry in which has the username or email does not exist, but when the username or email does exist i get these errors in the screenshot below yet i expect the stored procedure to return a simple select indicating where the problem could be or indicated success as the in case when it returns 'created'
Problem 2
If it is a unique entry and it gets inserted into the table, the password column cell in that particular row gets inserted with an empty string.
What could be the cause of all the above? Thanks you.
Perhaps these changes are what you are looking for. Changes to the schema, and your if blocks, and return values.
The return value is the AUTO_INCREMENT of the user id. Note, I pretty much followed your schema. Your Primary Key in that table could probably be collapsed a bit. Some might go lean with no user id or user name, but just the email address as the PK. Those are things to think about. I also added a unique key for email address.
Schema:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int auto_increment primary key,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`email` varchar(60) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varbinary(128) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`date_joined` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_category_id` tinyint(3) unsigned NOT NULL,
unique key (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- truncate table user;
Stored Procedure:
drop procedure if exists sp_create_account;
DELIMITER $$
CREATE PROCEDURE `sp_create_account`
( username_param VARCHAR(40),
email_param VARCHAR(60),
pass VARCHAR(30),
category_id TINYINT
)
BEGIN
DECLARE salt VARCHAR(60);
DECLARE username_var VARCHAR(40);
DECLARE email_var VARCHAR(60);
DECLARE recFound int;
DECLARE foundStatus int DEFAULT 0;
SELECT user_id INTO recFound FROM user WHERE username = username_param;
IF recFound is null THEN
SELECT user_id INTO recFound FROM user WHERE email = email_param;
IF recFound is not null THEN
SET foundStatus=1;
END IF;
ELSE
SET foundStatus=1;
END IF;
IF foundStatus=0 THEN
SET salt = '#4$^7EC%?';
SET salt = CONCAT( username_param, salt );
INSERT INTO user (username,email,password,active,date_joined,user_category_id) VALUES
( username_param, email_param, AES_ENCRYPT( pass, salt ), DEFAULT, DEFAULT, category_id );
set recFound=LAST_INSERT_ID();
END IF;
SELECT recFound;
END$$
DELIMITER ;
Test:
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('caspar','caspar001#gmail.com','thepass02',77);
select * from user;
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
| user_id | username | email | password | active | date_joined | user_category_id |
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
| 1 | Katherine | ksmith#hotmail.com | _╦*Fó▄GàB╔┌O►²§' | 1 | 2016-07-13 17:56:54 | 101 |
| 2 | caspar | caspar001#gmail.com | ♀½B§5U├↨I♀#*├ ∟L | 1 | 2016-07-13 17:57:09 | 77 |
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
2 rows in set (0.00 sec)
Your last ELSE needs to have all the commands you expect to execute in it enclosed in BEGIN ... END. Maybe? I've been working more in MSSQL lately.
I'm experiencing a 'Column cannot be null' error for 2 columns, when I try to run a SP.
Source table A is defined as below:
CREATE TABLE `test_data`.`offer` (
`id` INT NOT NULL,
`hotel_id` INT NOT NULL,
`currency_id` INT NOT NULL,
`source_system_code` VARCHAR(64) NOT NULL,
`available_cnt` INT NOT NULL,
`sellings_price` FLOAT NOT NULL,
`checkin_date` DATE NOT NULL,
`checkout_date` DATE NOT NULL,
`valid_offer_flag` TINYINT(1) NOT NULL,
`offer_valid_from` DATETIME NOT NULL,
`offer_valid_to` DATETIME NOT NULL,
`breakfast_included_flag` TINYINT(1) NOT NULL,
`insert_datetime` DATETIME NOT NULL,
PRIMARY KEY (`id`));
Table B into which I am inserting the data:
CREATE TABLE `calculate_USD` (
`counter` int(11) NOT NULL AUTO_INCREMENT,
`dates` date DEFAULT NULL,
`id` int(11) NOT NULL,
`hotel_id` int(11) NOT NULL,
`original_price` int(11) NOT NULL,
`currency_id` int(11) NOT NULL,
PRIMARY KEY (`counter`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Here is the SP for the insertion:
CREATE PROCEDURE `test_procedure`()
BEGIN
DECLARE aid INT;
DECLARE avalid_from_date DATE;
DECLARE avalid_to_date DATE;
DECLARE hotel_id INT;
DECLARE original_price float;
DECLARE currency_id int;
DECLARE tempdt DATE;
DECLARE done INT DEFAULT FALSE;
DECLARE getdates CURSOR FOR
SELECT id,offer_valid_from,offer_valid_to,hotel_id,sellings_price,currency_id
from offer;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN getdates;
read_loop: LOOP
FETCH getdates
INTO aid,avalid_from_date,avalid_to_date,hotel_id,original_price,currency_id;
IF done THEN
LEAVE read_loop;
END IF;
set tempdt=date(avalid_from_date);
WHILE (tempdt <= date(avalid_to_date)) do
insert into calculate_USD(dates,id,hotel_id,original_price,currency_id)
values(tempdt,aid,hotel_id,original_price,currency_id);
set tempdt=tempdt+INTERVAL 1 DAY;
end while;
END LOOP;
CLOSE getdates;
END
//
When I call the SP,
hotel_id & currency_id columns are instigating the error code.
If I assign them both NULL default values, the SP runs however, the hotel_id & currency_id values being inserted are all NULL like so (rest are OK):
counter | dates | id | hotel_id | original_price | currency_id |
1 | 2015-4-30 | 342523| NULL | 200 | NULL |
2 | 2015-4-30 | 342524| NULL | 112 | NULL |
This is strange, because both have valid data in the source table.
Please advise.
One option that can solve is:
.
.
.
DECLARE `getdates` CURSOR FOR
SELECT
`id`,
`offer_valid_from`,
`offer_valid_to`,
-- `hotel_id`,
`offer`.`hotel_id`,
`sellings_price`,
-- `currency_id`
`offer`.`currency_id`
FROM
`offer`;
.
.
.
So I figured it out.
All I had to do was re-name the hotel_id & currency_id variables in the SP to something else and it worked.
Updated SP:
delimiter //
CREATE PROCEDURE `test_procedure`()
BEGIN
DECLARE aid INT;
DECLARE avalid_from_date DATE;
DECLARE avalid_to_date DATE;
DECLARE sp_hotel_id INT;
DECLARE original_price float;
DECLARE sp_currency_id int;
DECLARE tempdt DATE;
DECLARE done INT DEFAULT FALSE;
DECLARE getdates CURSOR FOR
SELECT id,offer_valid_from,offer_valid_to,hotel_id,sellings_price,currency_id
from offer;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN getdates;
read_loop: LOOP
FETCH getdates
INTO aid,avalid_from_date,avalid_to_date,sp_hotel_id,original_price,sp_currency_id;
IF done THEN
LEAVE read_loop;
END IF;
set tempdt=date(avalid_from_date);
WHILE (tempdt <= date(avalid_to_date)) do
insert into calculate_USD(dates,id,hotel_id,original_price,currency_id)
values(tempdt,aid,sp_hotel_id,original_price,sp_currency_id);
set tempdt=tempdt+INTERVAL 1 DAY;
end while;
END LOOP;
CLOSE getdates;
END
//
call test_procedure();
I have a stored procedure, that checks if there is a user with the same e-mail address as the input, if not, then registeres one.
Here is the table:
CREATE TABLE IF NOT EXISTS `overkill`.`accounts` (
`accountID` INT NOT NULL AUTO_INCREMENT ,
`email` VARCHAR(64) NOT NULL ,
`firstName` VARCHAR(32) NOT NULL ,
`lastName` VARCHAR(32) NOT NULL ,
`passSaltedSHA` BINARY(20) NOT NULL ,
`salt` BINARY(20) NOT NULL ,
`gender` ENUM('m','f') NOT NULL ,
`birthDate` DATE NOT NULL ,
`regTime` TIMESTAMP NOT NULL ,
PRIMARY KEY (`accountID`) )
ENGINE = InnoDB;
Here is the stored procedure:
DELIMITER $$
CREATE PROCEDURE `overkill`.`registerUser` (
IN emailIN VARCHAR(64),
IN passwordIN VARCHAR(16),
IN firstNameIN VARCHAR(32),
IN lastNameIn VARCHAR(32),
IN birthIN DATE,
IN genderIN ENUM('f','m'))
BEGIN
DECLARE existingMailAccLOG INT DEFAULT NULL;
DECLARE saltLOC CHAR(40);
DECLARE regSuccessLOC BOOLEAN DEFAULT FALSE;
SELECT COUNT(*) INTO existingMailAccLOG FROM `overkill`.`accounts` WHERE `accounts`.`email` = emailIN;
IF existingMailAccLOG = 0 THEN
SET saltLOC = SHA1(rand());
SET regSuccessLOC = TRUE;
INSERT INTO `overkill`.`accounts` (`email`, `firstName`, `lastName`, `passSaltedSHA`, `salt`, `gender`, `birthDate`) VALUES(emailIN, firstNameIN, lastNameIn, UNHEX(SHA1(CONCAT(passwordIN, saltLOC))), UNHEX(saltLOC), genderIN, birthIN);
END IF;
SELECT regSuccessLOC AS `registered`, saltLOC AS `salt`;
END
If I call:
CALL registerUser("abc#def.com", "pass", "firstn", "lastn", "2012-01-01", "f");
It inserts a line into the accounts table, but forgets to return the proper values that I set inside the IF
SET saltLOC = SHA1(rand());
SET regSuccessLOC = TRUE;
How is it even possible? Why are theese lines skipped and INSERT still gets executed, without mistake?
Try to add "#" in front of your variable names after DECLARE keyword. It can cause some confusion, as it is described here: MySQL: #variable vs. variable. Whats the difference? (Part2) and here: MySQL: #variable vs. variable. Whats the difference?
Within a BPM web application, I have a field for an invoice # on a particular page but I need for it to be auto generated every time a user attaches an invoice and views that page. That number must be unique and preferably auto-incremented. A value for the invoice # field can be displayed by querying from a table from an external MYSQL database. So every time a user lands on that particular page, a SELECT query statement can be fired.
On MYSQL end, how would I set this up? So basically, I would like to setup a query for that invoice # field where it will for run a query for example,
SELECT invoice_num FROM invoice_generator
and every time this query runs, it would return the next incremented number.
You can use mysql trigger concept here....
I have added one example here...
It will be very usefull for u (see this link also :http://www.freemindsystems.com/mysql-triggers-a-practical-example/)
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '',
`price` int(20) NOT NULL DEFAULT '0',
`other` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `products_name_idx` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `freetags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tag` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `freetagged_objects` (
`tag_id` int(20) NOT NULL DEFAULT '0',
`object_id` int(20) NOT NULL DEFAULT '0',
`tagged_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`module` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`tag_id`, `object_id`),
KEY `freetagged_objects_tag_id_object_id_idx` (`tag_id`, `object_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT_PRODUCTS_TAGS
DELIMITER ||
DROP TRIGGER IF EXISTS insert_products_tags;
||
DELIMITER ##
CREATE TRIGGER insert_products_tags AFTER INSERT ON products
FOR EACH ROW
BEGIN
DECLARE current_id integer;
DECLARE tag_id integer;
DECLARE next integer;
DECLARE tag_field varchar(255);
DECLARE next_sep integer;
DECLARE current_tag varchar(255);
DECLARE right_tag varchar(255);
-- We use the field other as comma-separated tag_field
SET tag_field = NEW.other;
-- Check for empty tags
IF (CHAR_LENGTH(tag_field) <> 0) THEN
-- Loop until no more ocurrencies
set next = 1;
WHILE next = 1 DO
-- Find possition of the next ","
SELECT INSTR(tag_field, ',') INTO next_sep;
IF (next_sep > 0) THEN
SELECT SUBSTR(tag_field, 1, next_sep - 1) INTO current_tag;
SELECT SUBSTR(tag_field, next_sep + 1, CHAR_LENGTH(tag_field)) INTO right_tag;
set tag_field = right_tag;
ELSE
set next = 0;
set current_tag = tag_field;
END IF;
-- Drop spaces between comas
SELECT TRIM(current_tag) INTO current_tag;
-- Insert the tag if not already present
IF (NOT EXISTS (SELECT tag FROM freetags WHERE tag = current_tag)) THEN
-- Insert the tag
INSERT INTO freetags (tag) values (current_tag);
SELECT LAST_INSERT_ID() INTO tag_id;
ELSE
-- Or get the id
SELECT id FROM freetags WHERE tag = current_tag INTO tag_id;
END IF;
-- Link the object tagged with the tag
INSERT INTO freetagged_objects
(tag_id, object_id, module)
values
(tag_id, NEW.id, 'products');
END WHILE;
END IF;
END;
##
Now If you execute an insert on products table:
INSERT INTO PRODUCTS
(name, price, other)
values
("product1", 2, "tag1, tag2,tag3 , tag 4");