error 1310 while creating mysql procedure - mysql
I'm newbie with mysql procedures and I need to create lip_StoreItem procedure on mysql, but i'm getting this error
"[Err] 1310 - End-label $$ without match"
What is wrong here? or where i can get more info about that? I've tried to look for a solution on google, but it's too big deal for me :)
DELIMITER $$
/* Save item */
DROP PROCEDURE IF EXISTS `lip_StoreItem` $$
CREATE PROCEDURE `lip_StoreItem` (IN iItemID INTEGER UNSIGNED,
IN iOwnerID INTEGER UNSIGNED,
IN iItemType MEDIUMINT UNSIGNED,
IN iAmount BIGINT,
IN iSlot INTEGER,
IN eLoc ENUM('VOID','INVENTORY','PAPERDOLL','WAREHOUSE','FREIGHT','CLANWH','MAIL','PET_INVENTORY','PET_PAPERDOLL'),
IN iEnchant SMALLINT UNSIGNED,
IN iDuration INTEGER,
IN iPeriod INTEGER,
IN iAttackType TINYINT,
IN iAttackVal SMALLINT,
IN iDefFire SMALLINT,
IN iDefWater SMALLINT,
IN iDefWind SMALLINT,
IN iDefEarth SMALLINT,
IN iDefHoly SMALLINT,
IN iDefUnholy SMALLINT,
IN iVariStat1 SMALLINT UNSIGNED,
IN iVariStat2 SMALLINT UNSIGNED,
IN iBlessed INTEGER,
IN iDamaged INTEGER,
IN iItemEnergy INTEGER,
IN iCustomFlags INTEGER UNSIGNED,
IN iItemVisType MEDIUMINT UNSIGNED)
NOT DETERMINISTIC
SQL SECURITY DEFINER
entry: BEGIN
DECLARE iRowCount INTEGER DEFAULT 0;
IF (iAmount <= 0) OR (iDuration = 0) OR (iPeriod = 0) OR (iOwnerID = 0) THEN -- OR (eLoc = 'VOID')
CALL `lip_DeleteItem`(iItemID);
LEAVE entry;
END IF;
INSERT LOW_PRIORITY INTO `items` (
`item_id`,
`owner_id`,
`item_type`,
`amount`,
`location`,
`slot`,
`enchant`
) VALUES (
iItemID,
iOwnerID,
iItemType,
iAmount,
eLoc,
iSlot,
iEnchant
) ON DUPLICATE KEY UPDATE
`owner_id` = iOwnerID,
`item_type` = iItemType,
`amount` = iAmount,
`location` = eLoc,
`slot` = iSlot,
`enchant` = iEnchant;
SET iRowCount = ROW_COUNT();
-- SELECT 'lip_StoreItem[303]', iRowCount;
-- TODO: ROW_COUNT() bug ???
CASE
WHEN iRowCount = 1 THEN -- insert new
BEGIN
IF iDuration > 0 THEN -- new item duration
INSERT LOW_PRIORITY INTO `items_duration` (
`item_id`,
`duration`
) VALUES (
iItemID,
iDuration
) ON DUPLICATE KEY UPDATE
`duration` = iDuration;
-- SELECT 'lip_StoreItem[316]', iItemID, iDuration, ROW_COUNT();
END IF;
IF iPeriod > 0 THEN -- new item period
INSERT LOW_PRIORITY INTO `items_period` (
`item_id`,
`period`
) VALUES (
iItemID,
iPeriod
) ON DUPLICATE KEY UPDATE
`period` = iPeriod;
-- SELECT 'lip_StoreItem[326]', iItemID, iPeriod, ROW_COUNT();
END IF;
IF ((iAttackType > -2) AND (iAttackVal > 0)) OR -- have attack or some defence in new item
(iDefFire > 0) OR (iDefWater > 0) OR
(iDefWind > 0) OR (iDefEarth > 0) OR
(iDefHoly > 0) OR (iDefUnholy > 0) THEN
INSERT LOW_PRIORITY INTO `items_attributes` (
`item_id`,
`attack_type`,
`attack_value`,
`defence_fire`,
`defence_water`,
`defence_wind`,
`defence_earth`,
`defence_holy`,
`defence_unholy`
) VALUES (
iItemID,
iAttackType,
iAttackVal,
iDefFire,
iDefWater,
iDefWind,
iDefEarth,
iDefHoly,
iDefUnholy
) ON DUPLICATE KEY UPDATE
`attack_type` = iAttackType,
`attack_value` = iAttackVal,
`defence_fire` = iDefFire,
`defence_water` = iDefWater,
`defence_wind` = iDefWind,
`defence_earth` = iDefEarth,
`defence_holy` = iDefHoly,
`defence_unholy` = iDefUnholy;
-- SELECT 'lip_StoreItem[353]', iItemID,iAttackType,iAttackVal,iDefFire,iDefWater,iDefWind,iDefEarth,iDefHoly,iDefUnholy,ROW_COUNT();
END IF;
IF (iVariStat1 > 0) OR (iVariStat2 > 0) THEN -- have some variation(augumentation) in new item
INSERT LOW_PRIORITY INTO `items_variation` (
`item_id`,
`stat1`,
`stat2`
) VALUES (
iItemID,
iVariStat1,
iVariStat2
) ON DUPLICATE KEY UPDATE
`stat1` = iVariStat1,
`stat2` = iVariStat2;
-- SELECT 'lip_StoreItem[365]', iItemID, iVariStat1, iVariStat2, ROW_COUNT();
END IF;
IF (iBlessed > 0) OR (iDamaged > 0) OR (iItemEnergy > 0) OR (iCustomFlags > 0) OR (iItemVisType > 0) THEN -- have some rare or custom flag in item
INSERT LOW_PRIORITY INTO `items_options` (
`item_id`,
`blessed`,
`damaged`,
`energy`,
`flags`,
`item_vis_type`
) VALUES (
iItemID,
iBlessed,
iDamaged,
iItemEnergy,
iCustomFlags,
iItemVisType
) ON DUPLICATE KEY UPDATE
`blessed` = iBlessed,
`damaged` = iDamaged,
`energy` = iItemEnergy,
`flags` = iCustomFlags,
`item_vis_type` = iItemVisType;
-- SELECT 'lip_StoreItem[381]', iItemID, iBlessed, iDamaged, iItemEnergy, iCustomFlags, ROW_COUNT();
END IF;
END;
WHEN (iRowCount = 0) OR (iRowCount = 2) OR (iRowCount = 3) THEN -- not changed or updated or Bug#46675(or toad for mysql future?)
BEGIN
IF iDuration > 0 THEN
UPDATE LOW_PRIORITY `items_duration` SET `duration` = iDuration WHERE `item_id` = iItemID LIMIT 1;
-- INSERT LOW_PRIORITY INTO `items_duration` (
-- `item_id`,
-- `duration`
-- ) VALUES (
-- iItemID,
-- iDuration
-- ) ON DUPLICATE KEY UPDATE
-- `duration` = iDuration;
-- SELECT 'lip_StoreItem[395]', iItemID, iDuration, ROW_COUNT();
END IF;
IF iPeriod > 0 THEN
UPDATE LOW_PRIORITY `items_period` SET `period` = iPeriod WHERE `item_id` = iItemID LIMIT 1;
-- INSERT LOW_PRIORITY INTO `items_period` (
-- `item_id`,
-- `period`
-- ) VALUES (
-- iItemID,
-- iPeriod
-- ) ON DUPLICATE KEY UPDATE
-- `period` = iPeriod;
-- SELECT 'lip_StoreItem[407]', iItemID, iDuration, ROW_COUNT();
END IF;
IF ((iAttackType > -2) AND (iAttackVal > 0)) OR -- have attack or some defence
(iDefFire > 0) OR (iDefWater > 0) OR
(iDefWind > 0) OR (iDefEarth > 0) OR
(iDefHoly > 0) OR (iDefUnholy > 0) THEN
INSERT LOW_PRIORITY INTO `items_attributes` ( -- add new or update old
`item_id`,
`attack_type`,
`attack_value`,
`defence_fire`,
`defence_water`,
`defence_wind`,
`defence_earth`,
`defence_holy`,
`defence_unholy`
) VALUES (
iItemID,
iAttackType,
iAttackVal,
iDefFire,
iDefWater,
iDefWind,
iDefEarth,
iDefHoly,
iDefUnholy
) ON DUPLICATE KEY UPDATE
`attack_type` = iAttackType,
`attack_value` = iAttackVal,
`defence_fire` = iDefFire,
`defence_water` = iDefWater,
`defence_wind` = iDefWind,
`defence_earth` = iDefEarth,
`defence_holy` = iDefHoly,
`defence_unholy` = iDefUnholy;
-- SELECT 'lip_StoreItem[443]', iItemID,iAttackType,iAttackVal,iDefFire,iDefWater,iDefWind,iDefEarth,iDefHoly,iDefUnholy,ROW_COUNT();
ELSE -- or delete (eg remove attribute)
DELETE LOW_PRIORITY FROM `items_attributes` WHERE `item_id` = iItemID LIMIT 1;
-- SELECT 'lip_StoreItem[447]', iItemID,iAttackType,iAttackVal,iDefFire,iDefWater,iDefWind,iDefEarth,iDefHoly,iDefUnholy,ROW_COUNT();
END IF;
IF (iVariStat1 > 0) OR (iVariStat2 > 0) THEN -- have some new variation(augumentation) in existing item
INSERT INTO `items_variation` (
`item_id`,
`stat1`,
`stat2`
) VALUES (
iItemID,
iVariStat1,
iVariStat2
) ON DUPLICATE KEY UPDATE
`stat1` = iVariStat1,
`stat2` = iVariStat2;
-- SELECT 'lip_StoreItem[462]', iVariStat1, iVariStat2, ROW_COUNT();
ELSE -- delete variation (variation was removed or newer exists)
DELETE LOW_PRIORITY FROM `items_variation` WHERE `item_id` = iItemID LIMIT 1;
-- SELECT 'lip_StoreItem[465]', iVariStat1, iVariStat2, ROW_COUNT();
END IF;
IF (iBlessed > 0) OR (iDamaged > 0) OR (iItemEnergy > 0) OR (iCustomFlags > 0) OR (iItemVisType > 0) THEN -- have some new rare or custom flag in item
INSERT LOW_PRIORITY INTO `items_options` (
`item_id`,
`blessed`,
`damaged`,
`energy`,
`flags`,
`item_vis_type`
) VALUES (
iItemID,
iBlessed,
iDamaged,
iItemEnergy,
iCustomFlags,
iItemVisType
) ON DUPLICATE KEY UPDATE
`blessed` = iBlessed,
`damaged` = iDamaged,
`energy` = iItemEnergy,
`flags` = iCustomFlags,
`item_vis_type` = iItemVisType;
-- SELECT 'lip_StoreItem[484]', iItemID, iBlessed, iDamaged, iItemEnergy, iCustomFlags, ROW_COUNT();
ELSE -- remove rare flags
DELETE LOW_PRIORITY FROM `items_options` WHERE `item_id` = iItemID LIMIT 1;
-- SELECT 'lip_StoreItem[487]', iItemID, iBlessed, iDamaged, iItemEnergy, iCustomFlags, ROW_COUNT();
END IF;
END;
ELSE
BEGIN
-- exception
-- SELECT 'lip_StoreItem[384] exception', iRowCount;
CALL `Unexpected ROW_COUNT() result in lip_StoreItem`;
END;
END CASE;
END $$
mysql answer what i get:
INSERT LOW_PRIORITY INTO `items_attributes` (
`item_id`,
`attack_type`,
`attack_value`,
`defence_fire`,
`defence_water`,
`defence_wind`,
`defence_earth`,
`defence_holy`,
`defence_unholy`
) VALUES (
iItemID,
iAttackType,
iAttackVal,
iDefFire,
iDefWater,
iDefWind,
iDefEarth,
iDefHoly,
iDefUnholy
) ON DUPLICATE KEY UPDATE
`attack_type` = iAttackType,
[Err] 1310 - End-label $$ without match
Related
Result consisted of more than one row - Procedure
I got this error message: Result consisted of more than one row but I check my procedure again and again but I cannot find any problem: DROP PROCEDURE IF EXISTS SP_Fetch_Returned_With_Serials; CREATE PROCEDURE `SP_Fetch_Returned_With_Serials`() BEGIN DECLARE Num BIGINT UNSIGNED DEFAULT 0; DECLARE __Product_Id bigint UNSIGNED DEFAULT NULL; DECLARE __Serials varchar(255) DEFAULT NULL; DECLARE done INT DEFAULT 0; DECLARE cur CURSOR FOR SELECT product_id, serials FROM tmp_table_returned_product_serial; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; START TRANSACTION ; SET #Document_Id = 0 ; SET #Product_Id = 0; SET #Payment_Amount = 0; OPEN cur; read_loop: LOOP IF done THEN LEAVE read_loop; END IF; FETCH cur INTO __Product_Id,__Serials; CALL SP_Separate_Numeric_Values(`__Serials`); SET #Is_Returnable = 0; SET #Level_Id = 0; SET #Free_Day = 0; SET #Penalty_Percent = 0; SET #Factor_Type_Id = 0; SET #Currency_Id = 0; SET #Customer_Id = 0; SET #Factor_Id = 0; SET #Value = 0; SET #Real_Fee = 0; SET #Date_At = CURRENT_DATE(); SET #Diff_Days = 0; SET #New_Factor_Id = 0; SET #New_Detail_Factor_Id = 0; SET #Receipt_Remit_Type_Id = 0; SET #Return_Penalty_Percent = 0; SET #Return_Penalty_Price = 0; SET #Document_Number = 0; SELECT id INTO #Factor_Type_Id FROM Tb_Factor_Types WHERE name = 'back_sale_factor'; SELECT COUNT(NV.Number) INTO #Value FROM Numeric_Values NV; SELECT TP.is_returnable, TU.level_id, currency_id, customer_id, VF.id, VF.product_id, real_fee, date_at INTO #Is_Returnable,#Level_Id,#Currency_Id,#Customer_Id,#Factor_Id,#Product_Id,#Real_Fee,#Date_At FROM Vw_Factor_Master_Details VF INNER JOIN Tb_Factor_Detail_Serials TFDS ON TFDS.detail_id = VF.detail_id INNER JOIN Tb_Products TP ON VF.product_id = TP.id INNER JOIN Tb_Users TU ON TU.user_id = VF.customer_id INNER JOIN Numeric_Values NV ON NV.Number = TFDS.serial_id; IF (#Is_Returnable) THEN SET #Product_Title = ''; SET #Error_Msg = ''; SELECT IFNULL(TPT.title, TP.title_en) AS title INTO #Product_Title FROM Tb_Products TP LEFT JOIN (SELECT title, product_id FROM Tb_Product_Translations WHERE locale = #Locale) TPT ON TP.id = TPT.product_id WHERE product_id = #Product_Id; SELECT message INTO #Error_Msg FROM Tb_Errors WHERE error_code = 1000028 AND locale = #Locale; SET #Error_Msg = REPLACE(#Error_Msg, ':product', #Product_Title); SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = #Error_Msg; END IF; SELECT DATEDIFF(CURRENT_DATE(), #Date_At) INTO #Diff_Days; SELECT MAX(`number`) INTO Num FROM Tb_Factors WHERE year_id = #Fiscal_Year AND type = 'sale_factor'; SET Num = ifnull(Num, 0) + 1; SELECT JSON_EXTRACT(JSON_EXTRACT(TS.value, CONCAT('$.', #Level_Id)), '$.free_day') INTO #Free_Day FROM Tb_Settings TS WHERE `key` = 'returned_product'; SELECT JSON_EXTRACT(JSON_EXTRACT(TS.value, CONCAT('$.', #Level_Id)), '$.penalty_percent') INTO #Penalty_Percent FROM Tb_Settings TS WHERE `key` = 'returned_product'; IF (#Diff_Days > #Free_Day) THEN SET #Payment_Amount = #Payment_Amount + ((#Real_Fee - (#Real_Fee * #Penalty_Percent / 100)) * #Value); SET #Return_Penalty_Percent = #Penalty_Percent; SET #Return_Penalty_Price = #Real_Fee * #Penalty_Percent / 100; END IF; IF(#New_Factor_Id = 0) THEN INSERT INTO Tb_Factors (type, sale_place, product_type, company_id, branch_id, cash_desk_id, type_id, year_id, currency_id, finaler_id, signature_id, customer_id, final_at, signature_at, reference_factor_id, creator_id, number) VALUES ('sale_factor', 'branch', 'product', #Company, #Branch_Id, NULL, #Factor_Type_Id, #Fiscal_Year, #Currency_Id, #Auth_User, #Auth_User, #Customer_Id, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP(), #Factor_Id, #Auth_User, Num); SET #New_Factor_Id = LAST_INSERT_ID(); END IF; INSERT INTO Tb_Factor_Details (product_id, value, real_fee, fee, factor_id, creator_id, return_penalty_percent, return_penalty_price) VALUES (#Product_Id, #Value, #Real_Fee, #Real_Fee, #New_Factor_Id, #Auth_User, #Penalty_Percent, #Return_Penalty_Price); SET #New_Detail_Factor_Id = LAST_INSERT_ID(); INSERT INTO Tb_Factor_Detail_Serials (serial_id, detail_id) SELECT NV.Number, #New_Detail_Factor_Id FROM Numeric_Values NV; SELECT id INTO #Receipt_Remit_Type_Id FROM Tb_Receipt_Remit_Types WHERE name = 'return_of_sales'; SET #Warehouse_Id = 0; SELECT id INTO #Warehouse_Id FROM Tb_Warehouses WHERE warehouse_branch_id = #Branch_Id LIMIT 1; IF(#Document_Id = 0) THEN SELECT document_number FROM Tb_Documents WHERE fiscal_year_id = #Fiscal_Year ORDER BY document_number DESC LIMIT 1 INTO #Document_Number; SET #Document_Number = #Document_Number + 1; INSERT INTO Tb_Documents (type, factor_id, warehouse_id, receipt_remit_type_id, fiscal_year_id, document_number, creator_id) VALUES ('receipt', #New_Factor_Id, #Warehouse_Id, #Receipt_Remit_Type_Id, #Fiscal_Year, #Document_Number, #Auth_User); SET #Document_Id = LAST_INSERT_ID(); END IF; INSERT INTO Tb_Document_Details (product_id, value, confirmed_at, confirmed_by, creator_id, document_id) VALUES (#Product_Id, #Value, CURRENT_TIMESTAMP(), #Auth_User, #Auth_User, #Document_Id); SET #Document_Detail_Id = LAST_INSERT_ID(); INSERT INTO Tb_Detail_Serial_Numbers (serial_number_id, detail_id, origin_cost_center_id, confirmed_at, confirmed_by) SELECT NV.Number, #Document_Detail_Id,NULL,CURRENT_TIMESTAMP(),#Auth_User FROM Numeric_Values NV; END LOOP; CLOSE cur; SET #Type_Id = 0; SELECT id INTO #Type_Id FROM Tb_Payment_Types WHERE name = 'cash' LIMIT 1; INSERT INTO Tb_Receive_Payment (model_type, model_id, factor_id, type_id, receive_amount, payment_amount,year_id,creator_id) VALUES ('cashdesk', NULL, #New_Factor_Id, #Type_Id, 0, #Payment_Amount,#Fiscal_Year,#Auth_User); SET #Payment_Id = LAST_INSERT_ID(); SELECT #Factor_Id as factor_id,#Payment_Id as payment_id,#Payment_Amount as payment_amount; COMMIT; END
Complex insert query with insert into and where subquery in Laravel
I am trying to figure out the best way to code this using Query Builder or Eloquent. In it's simplest form it should prevent insert of a new buy request if an item already in transactions table. I haven't found any useful reference other than running a complete raw query. INSERT INTO `transactions` (`user_id`, `item_id`, `type`, `created_at`, `updated_at`) SELECT 1, 186808, 'bought', NOW(), NOW() WHERE ( SELECT SUM( CASE WHEN `type` = 'bought' THEN 1 WHEN `type` = 'sold' THEN -1 END ) FROM `transactions` WHERE (`item_id`, `user_id`) = (186808, 1) GROUP BY `item_id` ) = 0
In Laravel, you can use DB::raw(<your_complex_query_here>) to achieve this. DB::raw("INSERT INTO `transactions` (`user_id`, `item_id`, `type`, `created_at`, `updated_at`) SELECT 1, 186808, 'bought', NOW(), NOW() WHERE ( SELECT SUM( CASE WHEN `type` = 'bought' THEN 1 WHEN `type` = 'sold' THEN -1 END ) FROM `transactions` WHERE (`item_id`, `user_id`) = (186808, 1) GROUP BY `item_id` ) = 0"); For more, refer to Laravel docs here https://laravel.com/docs/5.7/queries#raw-expressions
Mysql Procedure IF,ELSEIF Statment error
I try to create a procedure in mysql, but i get an syntax error, i don`t know why i get it and where is '' # 1064 - You have an error in the RSQL syntax next to '' on line 4 My Procedure: CREATE PROCEDURE MUWAP_VipAdd(IN szCharName varchar(10),IN DayAdd int,IN VipType smallint,IN datenow_srv datetime) BEGIN IF NOT EXISTS (SELECT 1 FROM `T_VIPList` WHERE AccountID = szCharName) THEN INSERT INTO `T_VIPList` (`AccountID`,`Date`,`Type`) VALUES (szCharName,DATE_ADD(datenow_srv, INTERVAL DayAdd DAY),VipType); ELSE IF EXISTS (SELECT 1 FROM `T_VIPList` WHERE AccountID = szCharName AND Date > datenow_srv) THEN UPDATE `T_VIPList` SET `Date` = DATE_ADD(`Date`,INTERVAL DayAdd DAY) WHERE `AccountID` = szCharName; UPDATE `T_VIPList` SET `Type` = VipType WHERE `AccountID` = szCharName AND `Type` < VipType; ELSE UPDATE `T_VIPList` SET `Date` = DATE_ADD(`Date`,INTERVAL DayAdd DAY), `Type` = VipType WHERE `AccountID` = szCharName; END IF END Thank you!
In order to have multiple statements in a THEN statement, you need to use BEGIN...END. CREATE PROCEDURE MUWAP_VipAdd(IN szCharName varchar(10),IN DayAdd int,IN VipType smallint,IN datenow_srv datetime) BEGIN IF NOT EXISTS (SELECT 1 FROM `T_VIPList` WHERE AccountID = szCharName) THEN INSERT INTO `T_VIPList` (`AccountID`,`Date`,`Type`) VALUES (szCharName,DATE_ADD(datenow_srv, INTERVAL DayAdd DAY),VipType); ELSE IF EXISTS (SELECT 1 FROM `T_VIPList` WHERE AccountID = szCharName AND Date > datenow_srv) THEN BEGIN UPDATE `T_VIPList` SET `Date` = DATE_ADD(`Date`,INTERVAL DayAdd DAY) WHERE `AccountID` = szCharName; UPDATE `T_VIPList` SET `Type` = VipType WHERE `AccountID` = szCharName AND `Type` < VipType; END ELSE UPDATE `T_VIPList` SET `Date` = DATE_ADD(`Date`,INTERVAL DayAdd DAY), `Type` = VipType WHERE `AccountID` = szCharName; END IF END You could also combine the two UPDATE queries into a single query: UPDATE T_VIPList SET Date = DATE_ADD(Date, INTERVAL DayAdd DAY), Type = GREATEST(VipType, Type) WHERE AccountID = szCharName; In fact, it seems like the whole thing could be done with a single INSERT ... ON DUPLICATE KEY UPDATE query: INSERT INTO T_VIPList (AccountID, Date, Type) VALUES (szCharName,DATE_ADD(datenow_srv, INTERVAL DayAdd DAY),VipType) ON DUPLICATE KEY UPDATE Date = IF(Date > datenow_srv, VALUES(Date), Date), Type = GREATEST(Type, VALUES(Type));
Rewrite MySQL Trigger to Postgres
guys! I have a trigger in MySQL database: CREATE DEFINER="root"#"127.0.0.1" TRIGGER `tai_actions_for_active_count` AFTER INSERT ON `actions` FOR EACH ROW BEGIN DECLARE l_isnn TINYTEXT; IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN SET l_isnn = IF(NEW.isnn is NULL, '*', NEW.isnn); IF NOT NEW.action_type = 'CLOSE' THEN INSERT INTO subscriptions.`statistics_active_count`(`service_id`, `operator_id`, `isnn`, `active_count`) VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1) ON DUPLICATE KEY UPDATE active_count = active_count + 1; ELSE SET #tai_actions_for_active_count = -1; UPDATE subscriptions.`statistics_active_count` SET active_count = #tai_actions_for_active_count := active_count - 1 WHERE `service_id` = NEW.service_id AND `operator_id` = NEW.operator_id AND `isnn` = l_isnn; IF #tai_actions_for_active_count = 0 THEN DELETE FROM subscriptions.`statistics_active_count` WHERE `active_count` = 0; END IF; END IF; END IF; END So I need to rewrite it to make it works in Postgres database. As there's ON DUPLICATE KEY UPDATE I'm using Postgres version 9.5 with UPSERT (ON CONFLICT (KEY) DO UPDATE). So I poorly know SQL language can you tell me what I'm doing wrong? There's the Postgres PL code: DECLARE l_isnn TEXT; tai_actions_for_active_count INTEGER; BEGIN IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN IF NEW.isnn is NULL THEN l_isnn := '*'; ELSE l_isnn := NEW.isnn; END IF; IF NOT NEW.action_type = 'CLOSE' THEN INSERT INTO "subscriptions.statistics_active_count"(service_id, operator_id, isnn, active_count) VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1) ON CONFLICT(active_count) DO UPDATE SET active_count = active_count + 1; ELSE tai_actions_for_active_count := -1; UPDATE "subscriptions.statistics_active_count" SET active_count = active_count - 1 -- (tai_actions_for_active_count := active_count - 1) WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn; UPDATE "subscriptions.statistics_active_count" SET tai_actions_for_active_count = active_count WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn; IF tai_actions_for_active_count = 0 THEN DELETE FROM "subscriptions.statistics_active_count" WHERE active_count = 0; END IF; END IF; END IF; RETURN NULL; END; As I want to test this trigger I'm getting an error -- relation "subscriptions.statistics_active_count" does not exist Can you help me with that code?
Finally I've got the solution. I guess :) BEGIN IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN IF NEW.isnn IS NULL THEN l_isnn := '*'; ELSE l_isnn := NEW.isnn; END IF; IF NOT NEW.action_type = 'CLOSE' THEN BEGIN INSERT INTO subscriptions.statistics_active_count (service_id, operator_id, isnn, active_count) VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1); EXCEPTION WHEN unique_violation THEN UPDATE subscriptions.statistics_active_count SET active_count = active_count + 1 WHERE service_id = NEW.service_id and operator_id=NEW.operator_id; END; ELSE tai_actions_for_active_count := -1; WITH upd AS (UPDATE subscriptions.statistics_active_count SET active_count = active_count - 1 WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn; RETURNING active_count) SELECT * FROM upd INTO tai_actions_for_active_count; IF tai_actions_for_active_count = 0 THEN DELETE FROM public.statistics_active_count WHERE active_count = 0; END IF; END IF; END IF; END;
Mysql Triggers with if statements and variables
Okay, so I am needing to create an after insert trigger that needs to use an if elseif and another elseif. The if, elseif, elseif need to be based on query data obtained from 3 other database tables. I was wondering if there was a way I could do this without having to run all three queries at the beginning. BEGIN SET #t3 = (SELECT team_id FROM team_trans WHERE key1 = NEW.trans_id LIMIT 1); SET #t2 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1); SET #t1 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0); IF (#t3) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t3, NEW.id, 0, 1 ); ELSEIF (#t1) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t1, NEW.id, 0, 1 ); ELSEIF (#t2) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t2, NEW.id, 0, 1 ); END IF; END
An option is: ... BEGIN /* SET #t3 = (SELECT team_id FROM team_trans WHERE key1 = NEW.trans_id LIMIT 1)// SET #t2 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1)// SET #t1 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0)// */ IF (SELECT #t3 := team_id FROM team_trans WHERE key1 = NEW.trans_id LIMIT 1) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t3, NEW.id, 0, 1); ELSEIF (SELECT #t1 := team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t1, NEW.id, 0, 1); ELSEIF (SELECT #t2 := team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1) THEN INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t2, NEW.id, 0, 1); END IF; END// ...