Mysql after insert trigger is giving error - mysql

I have written below after insert trigger and it didnt give me any error. But whenever I am trying to insert data into sept18.test I am getting below error
Error Code: 1442. Can't update table 'test' in stored function/trigger
because it is already used by statement which invoked this stored
function/trigger. 0.000 sec
Can someone please help me with this error. Thank you in adavance.
-- SELECT * FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME = 'TR_ORDERS_INS'
DROP TRIGGER IF EXISTS TR_ORDERS_INS;
DELIMITER $$
CREATE TRIGGER TR_ORDERS_INS
AFTER INSERT ON sept18.test for each row
BEGIN
DECLARE MAX_DATE1 DATETIME;
IF EXISTS
(
select 1 from ept18.test O
where O.STOREID = NEW.STOREID
AND O.ITEMID = NEW.ITEMID
AND O.ORDERDATE = NEW.ORDERDATE
)
THEN
SET MAX_DATE1 = (SELECT max(DateTimeStamp)
from sept18.test
where itemid = NEW.itemid
and storeid = NEW.storeid
and OrderDate = NEW.orderdate);
INSERT INTO sep18kentest.orders_history
(ORDERID,STOREID,ITEMID,ORDERDATE,QUANTITY,BONUSBUCK,FLATBONUSBUCK,PRICE,STOREPRICE,PRICEOVERRIDE,
PRICEOVERRIDEFLAG,DIRECTSHIPFLAG,FREEITEMFLAG,SRP,DATETIMESTAMP,RECORDNUMBER)
SELECT ORDERID,STOREID,ITEMID,ORDERDATE,QUANTITY,BONUSBUCK,FLATBONUSBUCK,PRICE,STOREPRICE,PRICEOVERRIDE,
PRICEOVERRIDEFLAG,DIRECTSHIPFLAG,FREEITEMFLAG,SRP,DATETIMESTAMP,RECORDNUMBER
FROM sept18.test OD
WHERE OD.storeid = NEW.storeid
and OD.itemid = NEW.itemid
and OD.orderdate = NEW.orderdate
and OD.DateTimeStamp < MAX_DATE1;
DELETE FROM sept18.test
WHERE storeid = NEW.storeid
and itemid = NEW.itemid
and orderdate = NEW.orderdate
and DateTimeStamp < MAX_DATE1;
END IF;
END$$

Related

With trigge move a row from one table where trigger exists to another table IN MYSQL

i have four table 1) Order 2)Order_log 3) Transection 4)Transection_log
When a Transection is complete and will update all the information, i want to move a row from Order table to Order_log and from Transection table move a row to Transection_log.
i am getting error
Error Code: 1442. Can't update table 'transaktion' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
I understand the problem but can not find any solution. Please can anyone help me;;beställning = Order , beställning_log = Order_log, transaktion_log = Transection_log, transaktion = Transection
CREATE DEFINER=`root`#`%` TRIGGER `TabortBeställning` AFTER UPDATE ON `transaktion` FOR EACH ROW BEGIN
if (select Betalning_Metod_ID from transaktion where new.Beställning_ID = Beställning_ID ) is not null And
(select Levererad_Datum from transaktion where new.Beställning_ID = Beställning_ID ) And
(select Status_ID from transaktion where new.Beställning_ID = Beställning_ID ) = 3
then
Insert Into beställning_log Select * From beställning Where Beställning_ID = New.Beställning_ID;
Delete From beställning Where Beställning_ID = New.Beställning_ID;
Insert Into transaktion_log Select * From transaktion Where Beställning_ID = New.Beställning_ID;
else
SIGNAL sqlstate '99999'
SET message_text = "Du har inte angett alla kolumn värden. Fyll på [Levererad Datum, Metod ID, Status ID ]";
END IF;
END

How to compare two tables SUM and Update another Table With MySql Trigger

compare two tables SUM and Update another Table With MySql Trigger
DELIMITER $$
CREATE TRIGGER change_com_status_on_sales_table AFTER INSERT ON `commision_calculation` // COMMISSION TABLE
FOR EACH ROW
BEGIN
DECLARE totalQnt1, totalQnt2 DOUBLE;
DECLARE sales_id INT;
SET #sales_id=(SELECT sales_info_id
FROM commercial_invoice WHERE ci_no = NEW.ci_no);
SET #totalQnt1=(SELECT sum(cc.quantity) as total_qnt1
FROM commision_calculation cc
LEFT JOIN commercial_invoice ci ON cc.ci_id = ci.id
WHERE cc.comission_type = 'Remex' AND ci.sales_info_id= #sales_id
GROUP BY #sales_id);
SET #totalQnt2=(SELECT SUM(sii.quantity) as total_income
FROM sales_info_item sii WHERE sii.sales_info_id = #sales_id
GROUP BY #sales_id);
IF (#totalQnt2 > #totalQnt1) THEN
UPDATE sales_information
SET ci_status = 'Partial'
WHERE id = #sales_id;
END IF;
IF (#totalQnt2 = #totalQnt1) THEN
UPDATE sales_information
SET ci_status = 'Full'
WHERE id = #sales_id;
END IF;
END; $$
DELIMITER ;
The error in above as mentioned by Jahid Hossain
I get "SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row"

MySQL if not exists by two columns update other

I want to insert record if it not exists by 2 columns, and if exists update column 3, here's the query:
INSERT INTO aktai_islaidos_id (akto_id, islaidos_id, savikaina)
SELECT * FROM (SELECT ? as a, ? as b, ? as c) AS tmp
WHERE NOT EXISTS (
SELECT akto_id, islaidos_id, savikaina FROM aktai_islaidos_id
WHERE akto_id = a AND islaidos_id = b
) ON DUPLICATE KEY UPDATE savikaina = VALUES(c);
Now I'm getting error what c not exists in fields list, I understand why, but I didn't know how to complete this query correctly and didn't find any examples like what only where selects duplicate all columns, thanks!
EDIT:
Figured out this with stored procedure:
CREATE PROCEDURE update(
IN akt_id INT,
IN isl_id INT,
IN sav INT)
BEGIN
IF (SELECT count(*) FROM aktai_islaidos_id WHERE akto_id = akt_id AND islaidos_id = isl_id) > 0 THEN
BEGIN
UPDATE aktai_islaidos_id SET savikaina = sav WHERE akto_id = akt_id AND islaidos_id = isl_id;
END;
ELSE
BEGIN
INSERT INTO aktai_islaidos_id (akto_id, islaidos_id, savikaina) VALUES (akt_id, isl_id, sav);
END;
END IF;
END

MySql Error 1054 when inserting into table that has trigger

I have created a trigger on a table, and when I try to insert data into it I get MySql error "Error Code: 1054 'unknown column license_key in field list'"
The INSERT I try to do is this:
INSERT INTO LOAD_MASTER(license_key, state, total_pageviews, total_visitors, max_visitors, max_pageviews, ip, secret, read_time, url)
VALUES ("order55555hytgtrfderfredfredfredftyu8ikloi98nhygt6", "preparing", 400, 1000, 200, 400, "202,2,35,36", "Hemmeligheden", 120, "http://google.dk");
The Trigger I have created is supposed to check the TABLE LOAD_STATS for the presence of the IP entered in the LOAD_MASTER table, and then based on the results change a value in another table called LICENSE
My trigger is here:
DELIMITER //
CREATE TRIGGER ip_check AFTER INSERT ON LOAD_MASTER FOR EACH ROW
BEGIN
DECLARE MK varchar(50);
DECLARE MIP varchar(15);
DECLARE LID int(6);
SET MK = license_key;
SET MIP = ip;
SET LID = (
SELECT l.license_id
FROM license_keys k, license l
WHERE l.license_id = k.license_id
AND k.license_key = MK
);
IF (SELECT COUNT(DISTICT(master_ip)) FROM LOAD_STATS WHERE master_ip = MIP AND master_key = MK ) > 3 THEN
UPDATE LICENSE
SET STATE = 0
WHERE license_id = LID;
END IF;
END
//
DELIMITER ;
Any help on why I get this error would be much appriciated.
-Dan
In these lines
SET MK = license_key;
SET MIP = ip;
you probably meant to address NEW.license_key and NEW.ip respectively.
IMHO you can make more succinct. Try this
DELIMITER //
CREATE TRIGGER ip_check
AFTER INSERT ON load_master
FOR EACH ROW
BEGIN
IF (SELECT COUNT(DISTICT(master_ip))
FROM load_stats
WHERE master_ip = NEW.ip
AND master_key = NEW.license_key ) > 3 THEN
UPDATE license
SET state = 0
WHERE license_id =
(
SELECT l.license_id
FROM license_keys k JOIN license l
ON l.license_id = k.license_id
AND k.license_key = NEW.license_key
); -- make sure that this subquery returns only ONE record
END IF;
END //
DELIMITER ;
There is some room for improvement rewriting an UPDATE with JOIN instead of using a subquery

stored procedure in mysql in ubuntu

I have created stored procedure in MySQL in Window-7. it run successfully on windows. But when I switch to Ubuntu it gives error in the stored procedure. On windows I am using SQLyog for creating stored procedure. On Ubuntu, I run the SQL script and call that stored procedure but it gives error. Below is my stored procedure.
DELIMITER $$
USE `adserver`$$
DROP PROCEDURE IF EXISTS `getDaypartTimeDetail`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `getDaypartTimeDetail`
(currentDate DATE,noOfdays INT,cityId BIGINT)
BEGIN
DECLARE i INT;
DECLARE dateCnt INT;
SET dateCnt = 0;
DROP TEMPORARY TABLE IF EXISTS OnlyDate;
DROP TEMPORARY TABLE IF EXISTS AdvScheduleData;
CREATE TEMPORARY TABLE OnlyDate(dday DATE);
CREATE TEMPORARY TABLE AdvScheduleData(dday BIGINT,daypartId INT,totalFile BIGINT,totalDur BIGINT);
/* Generate Dates */
WHILE(dateCnt < noOfdays) DO
SET i = 1;
INSERT INTO OnlyDate(dday) VALUES (DATE_ADD(currentDate, INTERVAL dateCnt DAY));
SET dateCnt = dateCnt + 1;
END WHILE;
/* Insert all dayparts for all dates */
INSERT INTO AdvScheduleData (dday, daypartID) SELECT (UNIX_TIMESTAMP(dday)*1000), id FROM OnlyDate, daypart;
/* Update total files and duration */
UPDATE AdvScheduleData SET
TotalFile = (SELECT COUNT(advt_id)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = AdvSch.advt_id
WHERE AdvScheduleData.dday BETWEEN AdvSch.start_date AND AdvSch.end_date
AND AdvSch.status = 2
AND AdvSch.active = 1
AND AdvSch.id IN (SELECT schedule_id FROM schedule_daypart
WHERE daypart_id = AdvScheduleData.daypartId )
AND AdvSch.id IN (SELECT schedule_id FROM schedule_cities WHERE city_id = cityId)
AND Adv.is_active = 1
AND Adv.is_deleted = 0
AND Adv.status = 2
AND Adv.expiry_date >= AdvScheduleData.dday),
totalDur = (SELECT SUM(Adv.duration)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = ADVSCH.advt_id
WHERE AdvScheduleData.dday BETWEEN AdvSch.start_date AND AdvSch.end_date
AND AdvSch.status = 2
AND AdvSch.active = 1
AND AdvSch.id IN (SELECT schedule_id FROM schedule_daypart
WHERE daypart_id = AdvScheduleData.daypartId )
AND AdvSch.id IN (SELECT schedule_id FROM schedule_cities WHERE city_id = cityId)
AND Adv.is_active = 1
AND Adv.is_deleted = 0
AND Adv.status = 2
AND Adv.expiry_date >= AdvScheduleData.dday);
SELECT * FROM AdvScheduleData;
END$$
DELIMITER ;
The output I get in Ubuntu is
mysql> call getDaypartTimeDetail('2012-08-13',5,30534); ERROR 1054
(42S22): Unknown column 'ADVSCH.advt_id' in 'on clause'
Table name and aliases are case sensitive in Ubuntu.
Hence, this reference is giving an error:
totalDur = (SELECT SUM(Adv.duration)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = ADVSCH.advt_id
Change it to AdvSch.advt_id