MYSQL TRIGGER with DECLARE value - mysql

I want to set value using declare on trigger. The trigger is as follow:
CREATE DEFINER=`root`#`localhost` TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note` FOR EACH ROW DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL SET
PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW. vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
ELSE:
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;"
But it returns error on saving
The following query has failed: "CREATE DEFINER=root#localhost
TRIGGER update_queue_after_insert AFTER INSERT ON encounter_note
FOR EACH ROW DECLARE is_exist INT; SET is_exist = ( SELECT count(*)
FROM practice_last_updated_module WHERE
What's wrong with the statement?

Use 13.6.1 BEGIN ... END Compound-Statement Syntax.
Try (maybe you need to use DELIMITER):
DELIMITER //
CREATE TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note`
FOR EACH ROW
BEGIN -- <- BEGIN
DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL
SET PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW.vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
-- ELSE:
ELSE
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;
END// -- <- END
DELIMITER ;

Related

Stored procedure not working properly via EXECUTE

I have the following stored procedure but it's not working properly. if call the procedure it gives a correct value but not updated the next value.
DROP procedure IF EXISTS `GetCommonSequenceReferenceData`;
CREATE PROCEDURE `GetCommonSequenceReferenceData`(
IN refData JSON
)
BEGIN
DECLARE sequ_id BIGINT;
DECLARE sequ_next_id BIGINT;
SELECT *
FROM COMMON_SEQ_REF_TB
WHERE seq_type = refData ->> "$.seq_type";
SET sequ_id = (SELECT seq_id
FROM COMMON_SEQ_REF_TB
WHERE seq_type = refData ->> "$.seq_type");
SET sequ_next_id = (SELECT next_id
FROM COMMON_SEQ_REF_TB
WHERE seq_type = refData ->> "$.seq_type");
IF (sequ_id IS NULL) THEN
SET sequ_next_id = 1;
INSERT INTO COMMON_SEQ_REF_TB (seq_type, next_id, created_at, updated_at)
VALUES (refData ->> "$.seq_type", sequ_next_id,
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());
ELSE
SET sequ_next_id = sequ_next_id + 1;
-- UPDATE START
UPDATE COMMON_SEQ_REF_TB
SET next_id = sequ_next_id,
updated_at = CURRENT_TIMESTAMP()
WHERE seq_type = refData ->> "$.seq_type";
END IF;
END;

What does "The following query failed" ";"" mean in MySQL?

While trying to update a trigger, MySQL tells me the query ";" failed. How is ";" even a query in MySQL's view is beyond me.
The exact message is:
The following query has failed: ";" MySQL said: #1065 - Query was empty
Here's the new trigger (AFTER INSERT):
BEGIN
DECLARE vIdPlacet VARCHAR(40);
DECLARE vTypeTravaux VARCHAR(32);
DECLARE vEssence VARCHAR(3) DEFAULT '-';
DECLARE vClasseHau VARCHAR(5) DEFAULT '-';
DECLARE vNoMesurag int;
DECLARE new_id_parcelle INT UNSIGNED DEFAULT 0;
DECLARE new_no_microplacette INT UNSIGNED DEFAULT 0;
IF NEW.deleted = 0 THEN
SELECT id_parcelle, no_microplacette
INTO new_id_parcelle, new_no_microplacette
FROM microplacette
WHERE id_microplacette = NEW.id_microplacette;
SELECT travaux, no_mesurag, id__placet
INTO vTypeTravaux, vNoMesurag, vIdPlacet
FROM secteur
LEFT JOIN parcelle ON secteur.id_secteur = parcelle.id_secteur
WHERE id_parcelle = new_id_parcelle;
IF vTypeTravaux = 'inventaire' THEN
SELECT abbreviation INTO vEssence FROM essences WHERE _id = NEW.id_essence;
IF NEW.hauteur_15 = 1 THEN
SET vClasseHau = '15CM+';
END IF;
IF (SELECT COUNT(*) FROM imported_pres_ess WHERE id__placet = vIdPlacet AND
caracteris = '-' AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_pres_ess (id__placet, caracteris, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, '-', vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF (SELECT COUNT(*) FROM imported_semi_gau WHERE id__placet = vIdPlacet AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_semi_gau (id__placet, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF NEW.diametre > 0 THEN
SET vClasseHau = 'D2_D8';
ELSE
SET vClasseHau = '-';
END IF;
IF (SELECT COUNT(*) FROM imported_pres_ess WHERE id__placet = vIdPlacet AND
caracteris = '-' AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_pres_ess (id__placet, caracteris, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, '-', vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF (SELECT COUNT(*) FROM imported_semi_gau WHERE id__placet = vIdPlacet AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_semi_gau (id__placet, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
END IF;
END IF;
END
I tried creating the procedure you show, but I don't get any error.
The error about "empty statement" happens when you try to execute a query through the API but the query string is empty.
I can duplicate the error in the mysql client this way:
mysql> set #s = '';
mysql> prepare stmt from #s;
ERROR 1065 (42000): Query was empty
So I suggest you look not at the stored procedure, but whatever code you're executing this from, and check that every time you try to execute a query, that you submit a non-empty string.
It turns out, the trigger I was updating got deleted in the meantime, so I was updating a trigger that didn't exist anymore.
I found out after refreshing the page (the trigger was gone from the trigger list).
I simply recreated the trigger anew and it worked.

MySQL: Procedure Loops, but only inserts once

CREATE DEFINER=`root`#`localhost` PROCEDURE `GenerateCharges2`()
BEGIN
Declare sumFunding LONG;
Declare done INT DEFAULT FALSE;
Declare invoiceCharge LONG;
Declare agencyID INT;
declare invoiceID int;
Declare fundingID INT;
Declare amountOfFunding LONG;
Declare getInvoiceData CURSOR For select invoices.idInvoices, invoices.idAgencies, invoices.InvoiceAmount, fundings.FundingBalance, fundings.idfundings from invoices
inner join agencies on invoices.idAgencies = agencies.idAgencies
inner join fundings on agencies.idAgencies = fundings.IdAgencies
where processed =0
group by invoices.idInvoices;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open getInvoicedata;
ze_loop: Loop
Fetch getInvoiceData into invoiceID, agencyID, invoiceCharge, amountOfFunding, fundingID;
if done then leave ze_loop;
end if;
if amountOfFunding > invoiceCharge then
insert into charges VALUES (invoiceCharge, invoiceID, fundingID);
end if;
end loop;
close getInvoiceData;
END
My issue is that if you were to insert a select statement, it runs a proper amont of times. However, the insert statement only inserts once with sample data. In every case, amnountOfFunding is ALWAYS greater than invoiceCharge. Desired results is to have all inserts happen for rows fetched.
I have this loop and insert every record that i need! Maybe you can modifiy or update yours loop with that!
DECLARE done INT DEFAULT FALSE ;
DECLARE l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria VARCHAR (100) ;
DECLARE l_precio DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_un_1 INT (20) DEFAULT 0 ;
DECLARE l_un_2 INT (20) DEFAULT 0 ;
DECLARE l_clp_1 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_clp_2 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE contador INT DEFAULT 0 ;
DECLARE valores CURSOR FOR
SELECT
local_formato_retail_codigo,
producto_sku,
producto_descripcion_sra,
producto_marca,
producto_categoria
FROM
base_comercial
WHERE mes_fecha = fecha
GROUP BY producto_sku,
local_formato_retail_codigo
ORDER BY local_formato_retail_codigo ASC,
producto_sku ASC ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE ;
TRUNCATE precio_cd ;
OPEN valores ;
read_loop :
LOOP
FETCH valores INTO l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria ;
IF done
THEN LEAVE read_loop ;
END IF ;
SET l_clp_1 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_clp_2 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_1 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_2 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
IF (ISNULL(l_clp_1))
THEN SET l_clp_1 = 0 ;
END IF ;
IF (ISNULL(l_clp_2))
THEN SET l_clp_2 = 0 ;
END IF ;
IF (ISNULL(l_un_1))
THEN SET l_un_1 = 0 ;
END IF ;
IF (ISNULL(l_un_2))
THEN SET l_un_2 = 0 ;
END IF ;
SET l_precio = ((l_clp_1 + l_clp_2) / (l_un_1 + l_un_2)) ;
IF (ISNULL(l_precio))
THEN SET l_precio = 0 ;
END IF ;
INSERT INTO precio_cd
VALUES
(
l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria,
l_precio
) ;
END LOOP read_loop ;
CLOSE valores ;
SELECT
*
FROM
precio_cd ;

Mysql : Not allowed to return a result set from a function

I have write one function but getting this error Not allowed to return a result set from a function
DELIMITER $$
CREATE FUNCTION getTestFunction
(
p_ParentID int,
p_ListName nvarchar(50),
p_Type nvarchar(50),
p_Count int
)
RETURNS nvarchar(2000)
BEGIN
DECLARE p_KeyValue nvarchar(2000);
DECLARE p_ListValue nvarchar(2000);
DECLARE p_TextValue nvarchar(2000);
DECLARE p_ReturnValue nvarchar(2000);
DECLARE p_Key nvarchar(2000);
IF p_ParentID = 0 THEN
IF p_Count = 0 THEN
SET p_ReturnValue = '';
ELSE
SET p_ReturnValue = p_ListName;
END IF;
ELSE
SELECT p_KeyValue = ListName + '.' + Value
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
RETURN p_ReturnValue;
If p_Type = 'ParentKey' Or (p_Type = 'ParentList' AND p_Count > 0) THEN
SET p_ReturnValue = p_KeyValue;
ELSE
IF p_Type = 'ParentList' THEN
SET p_ReturnValue = p_ListValue;
ELSE
SET p_ReturnValue = p_TextValue;
END IF;
END IF;
IF p_Count > 0 THEN
If p_Count = 1 AND p_Type = 'ParentList' THEN
SET p_ReturnValue = p_ReturnValue + ':' + p_ListName;
ELSE
SET p_ReturnValue = p_ReturnValue + '.' + p_ListName;
END IF;
END IF;
END IF;
RETURN p_ReturnValue;
END$$
DELIMITER ;
You want to assign the result of a query to a variable, but in fact you're just selecting. That's why MySQL's complaining.
You have to change this
SELECT p_KeyValue = ListName + '.' + Value
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
to
SELECT CONCAT(ListName, '.', `Value`)
INTO p_KeyValue
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
And you should add an ORDER BY. A LIMIT without ORDER BY doesn't make sense, since there's no guaranteed order in a relational database.
Mysql complains about SELECT statement in your function,
probably it understands SELECT p_KeyValue = ListName + '.' + Value as comparison
change it to
SELECT CONCAT(ListName, '.', Value) INTO p_KeyValue

MySQL Stored Procedures issue with if then else statements

I have the need to store the changes in our invoice system to export it to the account system (which is a 3rd party app).
What I'm trying to do is to add two triggers.
ON INSERT : A new invoice is added, it has to be marked as new in another table, so in the next migration, generate the appropiate ASCII to import it in the accounting system.
ON UPDATE: This is a bit more complicated, this can happen when an invoice is modified or when an invoice becomes payed / or it was marked to be payed and finally it hasnt.
Both Triggers call the same procedure.
DROP PROCEDURE IF EXISTS `marca_factura_modificada`;
DELIMITER |
CREATE PROCEDURE `marca_factura_modificada`( IN nempresa_in int, IN nfactura_in int, IN cany_in char(2), IN cobrada boolean )
BEGIN
DECLARE existeix_factura INT;
DECLARE abans_afegir_factura INT;
DECLARE abans_afegir_cobrament INT;
SELECT NFactura,afegir_factura,afegir_cobrament
INTO existeix_factura,abans_afegir_factura,abans_afegir_cobrament
FROM factures_modificades
WHERE NEmpresa = nempresa_in
AND NFactura = nfactura_in
AND CAny = cany_in
LIMIT 1;
IF existeix_factura IS NULL THEN
IF new.DataFactura = CURDATE() THEN
IF (new.LComptat = 1 OR new.LCreditCobrat = 1) THEN
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,1,1);
ELSE
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,1,0);
END IF
ELSE
/* Si no és d'avui i no hi ha registre es que ja es va afegir la factura en el seu dia */
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,0,1);
END IF
ELSE
IF(cobrada = 0 AND abans_afegir_factura = 0) THEN
DELETE FROM factures_modificades WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in LIMIT 1;
ELSEIF (cobrada = 1 AND abans_afegir_cobrament = 0) THEN
UPDATE factures_modificades SET afegir_cobrament = 1 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
ELSEIF (cobrada = 0 AND abans_afegir_cobrament = 1) THEN
UPDATE factures_modificades SET afegir_cobrament = 0 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
END IF
END IF
END
|
DELIMITER ;
But this doesnt work on mysql 5.5 (I think there is some issue in IF THEN ELSE code, but I dont see where.
Solved!
Now it works. The problem was END IF wants a ; in the end.
DROP PROCEDURE IF EXISTS `marca_factura_modificada`;
DELIMITER |
CREATE PROCEDURE `marca_factura_modificada`( IN nempresa_in int, IN nfactura_in int, IN cany_in char(2), IN cobrada boolean,IN DataFactura date )
BEGIN
DECLARE existeix_factura INT;
DECLARE abans_afegir_factura INT;
DECLARE abans_afegir_cobrament INT;
SELECT NFactura,afegir_factura,afegir_cobrament
INTO existeix_factura,abans_afegir_factura,abans_afegir_cobrament
FROM factures_modificades
WHERE NEmpresa = nempresa_in
AND NFactura = nfactura_in
AND CAny = cany_in
LIMIT 1;
IF (existeix_factura) IS NULL THEN
IF (DataFactura = CURDATE()) THEN
IF (cobrada) THEN INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,1,1);
ELSE INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,1,0);
END IF;
ELSE INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,0,1);
END IF;
ELSE
IF(cobrada = 0 AND abans_afegir_factura = 0) THEN DELETE FROM factures_modificades WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in LIMIT 1;
ELSEIF (cobrada = 1 AND abans_afegir_cobrament = 0) THEN UPDATE factures_modificades SET afegir_cobrament = 1 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
ELSEIF (cobrada = 0 AND abans_afegir_cobrament = 1) THEN UPDATE factures_modificades SET afegir_cobrament = 0 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
END IF;
END IF;
END
|
DELIMITER ;