Dynamic name tablе in trigger - mysql

There is a trigger that copies columns from one table to another. How do I assign a table name to a dynamic variable #nametable?
Every day the name of the table changes depending on the current date.
USE dbo;
DROP TRIGGER IF EXISTS `update_test`;
GO
DELIMITER |
CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
DECLARE nametable VARCHAR(128);
SET #nametable =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
INSERT INTO `dbo`.`nametable` SET
`TIME_` =NEW.`recorded`,
`P1` = NEW.`value1`
ON DUPLICATE KEY UPDATE
`TIME_` = NEW.`recorded`,
`P1` = NEW.`value1`;
END;
Have error ERROR 1146: Table 'dbo.nametable' doesn't exist

I decided to do so as a temporary solution:
CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
SET #dateNameTableNOW =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
SET #dateNameTableSELECT1 = '06122017_v';
SET #dateNameTableSELECT2 = '07122017_v';
IF(#dateNameTableNOW = #dateNameTableSELECT1) THEN
INSERT INTO dbo.06122017_v SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;
IF(#dateNameTableNOW = #dateNameTableSELECT2) THEN
INSERT INTO dbo.07122017_v SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;
END;

Related

update a table after inserting a value in the same table using triggers [duplicate]

I am running a MySQL Query. But when a new row is added from form input I get this error:
Error: Can't update table 'brandnames' in stored function/trigger because it is
already used by statement which invoked this stored function/trigger.
From the code:
CREATE TRIGGER `capital` AFTER INSERT ON `brandnames`
FOR EACH
ROW UPDATE brandnames
SET bname = CONCAT( UCASE( LEFT( bname, 1 ) ) , LCASE( SUBSTRING( bname, 2 ) ) )
What does this error mean?
You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.
However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values --if doing an UPDATE-- with OLD.
If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:
CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END
The correct syntax is:
FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
, LCASE( SUBSTRING( NEW.bname, 2 ) ) )
A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id will compile, but not actually work since NEW.id will always be 0:
create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey =
(select surrogatekey from surrogatekeys where id = NEW.id);
#gerrit_hoekstra wrote: "However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case."
That is correct but you can select the auto-increment field value that will be inserted by the subsequent INSERT quite easily. This is an example that works:
CREATE DEFINER = CURRENT_USER TRIGGER `lgffin`.`variable_BEFORE_INSERT` BEFORE INSERT
ON `variable` FOR EACH ROW
BEGIN
SET NEW.prefixed_id = CONCAT(NEW.fixed_variable, (SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'lgffin'
AND TABLE_NAME = 'variable'));
END
I have the same problem and fix by add "new." before the field is updated. And I post full trigger here for someone to want to write a trigger
DELIMITER $$
USE `nc`$$
CREATE
TRIGGER `nhachung_province_count_update` BEFORE UPDATE ON `nhachung`
FOR EACH ROW BEGIN
DECLARE slug_province VARCHAR(128);
DECLARE slug_district VARCHAR(128);
IF old.status!=new.status THEN /* neu doi status */
IF new.status="Y" THEN
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
ELSE
UPDATE province SET `count`=`count`-1 WHERE id = new.district_id;
END IF;
ELSEIF old.province_id!=new.province_id THEN /* neu doi province_id + district_id */
UPDATE province SET `count`=`count`+1 WHERE id = new.province_id; /* province_id */
UPDATE province SET `count`=`count`-1 WHERE id = old.province_id;
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id; /* district_id */
UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;
SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);
ELSEIF old.district_id!=new.district_id THEN
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;
SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);
END IF;
END;
$$
DELIMITER ;
Hope this help someone

Update Data When Trigger Execute in Mysql?

I want WaterRateMeterStart with WaterRateMeterEnd have same value sequentially if data updated.
This is my table
And This is my table structure
This my code and
I do not know how mistakes can occur.
DELIMITER $$
CREATE TRIGGER after_update_rates_water_again AFTER UPDATE ON waterrates FOR EACH ROW
BEGIN
IF
new.WaterRateMeterStart <> old.WaterRateMeterStart THEN
UPDATE waterrates
SET WaterRateMeterEnd = new.WaterRateMeterStart
WHERE
WaterRateId = ( new.WaterRateId - 1 );
ELSEIF new.WaterRateMeterEnd <> old.WaterRateMeterEnd THEN
UPDATE waterrates
SET WaterRateMeterStart = new.WaterRateMeterEnd
WHERE
WaterRateId = ( new.WaterRateId + 1 );
END IF;
END $$
DELIMITER ;
And error if I updated the data
UPDATE `waterrates` SET `WaterRateMeterStart` = '9' WHERE `waterrates`.`WaterRateId` = 2

MySQL - Insert Into 2 Tables on 1 Procedure

I need to create a procedure for inserting records into 2 tables, but on the second table, I want to insert the last ID that was inserted on the first table. Could anyone help me with this?
This is my query
DELIMITER //
DROP PROCEDURE IF EXISTS ROOM_FEATURE_INSERT;
CREATE PROCEDURE ROOM_FEATURE_INSERT (propID INT, featID INT, featNme VARCHAR(50))
BEGIN
-- BEGIN CHECK
IF NOT EXISTS
(
SELECT rFeatureName FROM COMPANY_T3s71.PROPERTY_RFEATURE PRFE
INNER JOIN COMPANY_T3s71.ROOM_FEATURE RFEA ON PRFE.rFeatureID=RFEA.rFeatureID
WHERE BINARY rFeatureName = featNme AND propertyID = propID
)
AND
(
SELECT rFeatureName FROM COMPANY_T3s71.ROOM_VIEW
WHERE BINARY rFeatureName = featNme
)
THEN
-- IF NOT EXISTS INSERT INTO 1st TABLE
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
END IF;
-- END CHECK
-- BEGIN CHECK 2nd TABLE
IF NOT EXISTS
(
SELECT propertyID, rFeatureID FROM COMPANY_T3s71.PROPERTY_RFEATURE
WHERE rFeatureID = featID AND propertyID = propID
)
THEN
-- IF NOT EXISTS INSERT INTO 2nd TABLE
INSERT INTO COMPANY_T3s71.PROPERTY_RFEATURE (propertyID, rFeatureID) VALUES (propID, featID);
END IF;
-- END CHECK 2nd TABLE
END
DELIMITER ;
How do we pass the featID param, when we just inserted it on the first INSERT query?
Thank you before hand.
Use SET featID = LAST_INSERT_ID(); after the first query and then use the variable
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
SET featID = LAST_INSERT_ID();
However, if the data is not insert at anytime then you have to make query in the if block to set the value for featID.

Insert into change value if duplicate entry

I have this sql query:
INSERT INTO my_table
SELECT id, name, type
FROM other_table
I have this row: 1,bob,male
And I try insert: 1,bob,male
So, I have a duplicate entry error and I want change my insert value with an increment by one so after I would have two rows:
bob,male <=NOT UPDATED
bob,male
I don't want update the existing row, if I have a duplicate entry error. The insert increments the id value. So, I think ON DUPLICATE KEY isn't the solution.
UPDATE:
If I use a trigger like this:
DELIMITER |
CREATE TRIGGER incremente_primary BEFORE INSERT ON my_table FOR EACH ROW
BEGIN
IF( EXISTS( SELECT * FROM my_table )) THEN
SET NEW.id = NEW.id + 1;
END IF;
END |
DELIMITER ;
It doesn't work because a trigger can read only one line.
As per your requirement, you need to set auto_increment property for your id and then just insert other columns except id, so that it can be auto_increment like below-
INSERT INTO my_table (name,type)
SELECT name, type
FROM other_table;
If you just want to ignore if there is duplicate then you can use-
INSERT IGNORE INTO my_table
SELECT id,name, type
FROM other_table;
make sure that the primary key isn't the name or the type. Because you can input duplicate rows as long as you do not duplicate primary keys
I find a solution, i use a cursor:
DROP PROCEDURE proc_incremente;
DELIMITER |
CREATE PROCEDURE proc_incremente()
BEGIN
DECLARE var_name, var_type VARCHAR(100);
DECLARE var_id INT;
DECLARE end TINYINT(1) DEFAULT 0;
DECLARE cursor_incremente CURSOR
FOR SELECT * FROM other_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET end = 1;
OPEN cursor_incremente;
loop_cursor: LOOP
FETCH cursor_incremente INTO var_id, var_name, var_type;
IF end = 1 THEN
LEAVE loop_cursor;
END IF;
WHILE ( EXISTS( SELECT * my_table WHERE id = var_id) IS TRUE) DO
SET var_id = var_id + 1;
END WHILE;
INSERT INTO my_table(id,name,type) VALUES(var_id,var_name,var_type);
END LOOP;
CLOSE cursor_incremente;
END |
DELIMITER ;
CALL proc_incremente();

Update in mysql trigger not working

I'm creating a trigger to execute after an insert is done into my checkin table but my update statement is not working
DELIMITER $$
DROP TRIGGER IF EXISTS checkins_AINS$$
CREATE TRIGGER `checkins_AINS` AFTER INSERT ON `checkins` FOR EACH ROW
BEGIN
DECLARE client_id INT;
DECLARE duplicate_record INTEGER DEFAULT 0;
DECLARE bpoints INT;
DECLARE business_id INT;
DECLARE CONTINUE HANDLER FOR 1062 SET duplicate_record = 1;
SELECT checkinPoints, id INTO bpoints, business_id FROM businesses WHERE id = new.venue_id;
INSERT INTO clients_checkins_summary(client_id, venue_id, first_checkin, last_checkin,visits)
VALUES(new.client_id, new.venue_id, new.createAt, new.createAt,1);
INSERT INTO clients_points_summary(client_id, business_id,current_points)
VALUES(new.client_id, business_id,bpoints);
IF duplicate_record = 1
THEN
UPDATE clients_checkins_summary
SET last_checkin = new.createAt,
visits = visits + 1
WHERE client_id = new.client_id and venue_id = new.venue_id;
UPDATE clients_points_summary
SET current_points = current_points + bpoints
WHERE client_id = new.client_id and business_id = business_id;
END IF;
END$$
DELIMITER ;
Inserting:
insert into checkins(client_id,venue_id,points,createAt,updateAt)
values (52,19,1,now(),now());
for the first time works fine but when the case of update is trigger is entering into the if but is not update the value.
I trace the variables into a table and all the values are correct but update is not been updating anything.
I missing something?
am I missing something?
Possibly this
UPDATE clients_points_summary
SET current_points = current_points + bpoints
WHERE client_id = new.client_id and business_id = business_id;
The problem here is that your local variable business_id and the column name clients_points_summary.business_id are ambiguous. You could disambiguate as follows:
UPDATE clients_points_summary cps
SET cps.current_points = cps.current_points + bpoints
WHERE cps.client_id = new.client_id and cps.business_id = business_id;