MySQL trigger syntax error on insert after with variables - php

I am trying to track users sales based on the new transactions that come through. The transactions are assigned through our site and not their desktop application. It is giving me a syntax error, but I can't seem to figure out why.
This is my code:
DROP TRIGGER IF EXISTS AssignTrans;
DELIMITER $$
CREATE TRIGGER `testing_cake3`.`AssignTrans` AFTER INSERT ON `main_1` FOR EACH ROW
BEGIN
SET #t1 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 1);
SET #t2 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.GROUP_ID AND team_assignments.type = 0);
IF (#t1) THEN
INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t1, NEW.id, 0, 1 );
ELSE IF (#t2) THEN
INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (#t2, NEW.id, 0, 1 );
END IF;
END $$
DELIMITER ;

THe answer is CHANGING THE ELSE IF TO ElSEIF

Related

INSERT INTO with no SELECT throws: Error #1242: Subquery return more than 1 row

I am trying to insert data into my Database but my query throws the error #1242: Subquery returns more than one row
The table does get inserted 1 or 2 rows but then it throws this error.
Here is my query:
INSERT INTO candidato (nombres, apellidos, nombrePuesto, ciudadOrigen, ubicacionPuesto, reubicacion, empleadoActual, certificaciones, disponibilidad, sueldoActual, nivelIngles, beneficiosActuales, observacionesGen, expectativaSalarial, experienciaGen, actitud, expectativasPuesto, añosExperiencia, solicitante, staffingPlan, cubreCapacidades, observacionesTec, tipoCandidato)
VALUES ($nombres, $apellidos, $nombrePuesto, $ciudadOrigen, $ubicacionPuesto, $reubicacion, $empleadoActual, $certificaciones, $disponibilidad, $sueldoActual, $nivelIngles, $beneficiosActuales, $observacionesGen, $expectativaSalarial, $experienciaGen, $actitud, $expectativasPuesto, $añosExperiencia, $solicitante, $staffingPlan, $cubreCapacidades, $observacionesTec, $tipoCandidato);
I am also using a trigger that inserts data in another table when this one gets a new row inserted:
Here is the trigger:
DELIMITER $$
CREATE TRIGGER asignarNotificacionCandidatoPropuesto
AFTER INSERT ON CANDIDATO
FOR EACH ROW
BEGIN
SET #idSolicitud = (SELECT DISTINCT r.idSolicitud FROM REQUISICION AS r INNER JOIN STAFFING_PLAN AS s ON r.idRequisicion=s.requisicion INNER JOIN CANDIDATO AS c ON c.staffingPlan=NEW.staffingPlan);
INSERT INTO NOTIFICACION(fechaHora, tipo, contenido)
VALUES (NOW(), 'candidatoPropuesto', CONCAT("{", "'idCandidato' : '", NEW.idCandidato, "'}"));
-- ", ", "'idSolicitud' : '", #idSolicitud,
IF NEW.idCandidato IS NOT NULL THEN
BEGIN
INSERT INTO RECIBE(destinatario, notificacion)
VALUES(NEW.solicitante, (SELECT MAX(idNotificacion) FROM NOTIFICACION));
END;
END IF;
END $$
DELIMITER ;

Insert or Update if exists not having to use Primary Key

I am trying to update my db table by checking if my product_number column already exists. I know you can use the INSERT OR UPDATE ON DUPLICATE KEY but the column I am trying to use is not a primary key.
I found the following query on a stack post but I keep getting the error Unrecognized statement type. (near Duplicate) when I try run it using phpMyAdmin.
DECLARE #numrecords INT
SELECT #numrecords = count(*)
FROM users_remark
WHERE product_number = '444'
IF #numrecords > 0 THEN
UPDATE products
SET product_name = 'abc',
product_description = def,
product_detail = '',
product_price = '100',
product_price_canada = '200'
WHERE product_number = '444'
ELSE
INSERT INTO products (product_number, product_name, product_description, product_price)
VALUES (444, abc, def, 100)
END IF
Why is this query not working?
Is there a better way to achieve what I am trying to accomplish?
I created a procedure for you:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_or_update $$
CREATE PROCEDURE insert_or_update(pProduct_number INT, pProduct_name VARCHAR(200), pProduct_description VARCHAR(200), pProduct_detail VARCHAR(200), pProduct_price FLOAT(15,2), pProduct_price_canada FLOAT(15,2))
BEGIN
DECLARE numrecords INT;
SELECT count(*) INTO numrecords FROM products WHERE product_number = pProduct_number;
IF numrecords > 0 THEN
UPDATE products SET
product_name = pProduct_name,
product_description = pProduct_description,
product_detail = pProduct_detail,
product_price = pProduct_price,
product_price_canada = pProduct_price_canada
WHERE product_number = pProduct_number;
ELSE
INSERT INTO products (product_number, product_name, product_description, product_price)
VALUES (pProduct_number, pProduct_name, pProduct_description, pProduct_price);
END IF;
END $$
DELIMITER ;
To call just:
CALL insert_or_update(444, , 'abc', 'def', '', '100', '444');

How do I CALL mysql TEMPORARY TABLE from CodeIgniter?

I have written a stored procedure in mysql which will create a TEMPORARY TABLE, I want to access the data of TEMPORARY TABLE using Codeigniter.But when I call "$this->db->query()" it returns empty data.
$data=array();
$call_procedure = "CALL sp_Stock()";
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);
I have changed my way to show the data. And I do changes it on stored procedure.
DELIMITER $$
CREATE PROCEDURE sp_Stock()
BEGIN
DECLARE cursor_finish INTEGER DEFAULT 0;
DECLARE m_numofpurchaseBag DECIMAL(10,2)DEFAULT 0;
DECLARE m_purchasedKg DECIMAL(10,2)DEFAULT 0;
DECLARE m_purBagDtlId INTEGER DEFAULT 0;
DECLARE stockCursor CURSOR FOR
SELECT purchase_bag_details.`actual_bags`,
(purchase_bag_details.`net`*purchase_bag_details.`actual_bags`) AS PurchasedKg,
purchase_bag_details.`id` AS PurchaseBagDtlId
FROM
purchase_invoice_detail
INNER JOIN
purchase_bag_details
ON purchase_invoice_detail.`id`= purchase_bag_details.`purchasedtlid`
INNER JOIN
`do_to_transporter`
ON purchase_invoice_detail.`id` = do_to_transporter.`purchase_inv_dtlid`
WHERE purchase_invoice_detail.`teagroup_master_id`=6
AND purchase_invoice_detail.`id`=1481
AND do_to_transporter.`in_Stock`='Y';
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET cursor_finish = 1;
DROP TEMPORARY TABLE IF EXISTS StockTable;
#temptable creation
CREATE TEMPORARY TABLE IF NOT EXISTS StockTable
(
purchaseBagDtlId INT,
purchasedBag NUMERIC(10,2),
purchasedKg NUMERIC(10,2),
blendedBag NUMERIC(10,2),
blendedKg NUMERIC(10,2),
stockBag NUMERIC(10,2),
stockKg NUMERIC(10,2)
);
#temptable creation
OPEN stockCursor ;
get_stock : LOOP
FETCH stockCursor INTO m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId;
IF cursor_finish = 1 THEN
LEAVE get_stock;
END IF;
/*SELECT m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId; */
/* Blending bag query*/
SET #m_numberofBlndBag:=0;
SET #m_BlndKg:=0;
/* Blend bag*/
SELECT #m_numberofBlndBag:=SUM(blending_details.`number_of_blended_bag`) AS belendedBag INTO #m_numberofBlndBag
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
#Blend Bag
#Blend Kgs
SELECT #m_BlndKg:=SUM(blending_details.`qty_of_bag` * blending_details.`number_of_blended_bag`) AS blendkg INTO #m_BlndKg
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
SET #m_StockBag:=(m_numofpurchaseBag - #m_numberofBlndBag);
SET #m_StockKg:=(m_purchasedKg - #m_BlndKg);
INSERT INTO StockTable
(
purchaseBagDtlId ,
purchasedBag ,
purchasedKg ,
blendedBag ,
blendedKg ,
stockBag ,
stockKg
)VALUES(m_purBagDtlId,m_numofpurchaseBag,m_purchasedKg,#m_numberofBlndBag,#m_BlndKg,#m_StockBag,#m_StockKg);
END LOOP get_stock;
CLOSE stockCursor;
SELECT * FROM StockTable;
#DROP TABLE StockTable;
END$$
DELIMITER ;
#CALL sp_Stock();
Anywhere I am using a temp table I am executing this before the temp table is created:
$this->db->query('DROP TABLE IF EXISTS StockTable');
I seem to remember reading someone having the same problem as you and for some reason you have to execute the above first.
So try:
$data=array();
$call_procedure = "CALL sp_Stock()";
$this->db->query('DROP TABLE IF EXISTS StockTable');
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);

trigger after insert on table 1, insert on table 2 with where condition column from table 1

My trigger is not working at all.
DELIMITER $$
CREATE TRIGGER leave_credit_nt
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO nonteaching_leavecredit (IdNum, Date_Hired, Emp_Stat, Date_Leave_Ac, Vac_Leave, Sick_Leave)
VALUES (new.IdNum, new.Date_Hired, new.Emp_Stat, new.Date_Hired + INTERVAL 1 YEAR, 0, 0)
WHERE employees.Emp_Type = 'NON-TEACHING';
END $$
DELIMITER
I want that the trigger will insert values into my second table only those with employees.emp_type = 'NON-TEACHING'. Can someone help me get this trigger working?
emp_type is a column in my table employees.
Your INSERT query is wrong. MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail.
You cant use WHERE condition with INSERT query. If you are using WHERE condition, it means you already have that row in the table. So , you should use UPDATE query instead of INSERT.
You can add conditional logic to your trigger with:
if new.Emp_Type = 'NON-TEACHING' then
INSERT INTO nonteaching_leavecredit (IdNum, Date_Hired, Emp_Stat, Date_Leave_Ac, Vac_Leave, Sick_Leave)
VALUES (new.IdNum, new.Date_Hired, new.Emp_Stat, new.Date_Hired + INTERVAL 1 YEAR, 0, 0);
end if;

how to update multiple columns from a trigger MySQL

hi i am using mysql trigger to update a table on another table's insertion
this trigger works fine
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 WHERE NEW.SubjectID = SubjectID;
END$$
but this gives an error
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 , AverageMarks = (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID ) WHERE NEW.SubjectID = SubjectID;
END$$
how to write this correctly , please help . thanks in advance .
Apparently there were problems when sub-queries were used:
Can you try splitting the SQL statement:
DELIMITER $$
CREATE TRIGGER `update_pupil_subject`
AFTER INSERT
ON `pupil_marks`
FOR EACH ROW
BEGIN
DECLARE avg_marks float;
SELECT AVG(Marks)
INTO avg_marks
FROM pupil_marks
WHERE NEW.SubjectID = SubjectID;
UPDATE pupil_subjects
SET NumberOfStudens = NumberOfStudens + 1, AverageMarks = avg_marks
WHERE NEW.SubjectID = SubjectID;
END
$$
Edit: Use
SHOW TRIGGERS WHERE `table` = 'pupil_marks';
to get all triggers defined on pupil_marks. You can't have multiple triggers on an event as all actions can be covered in single trigger.
NOTE: I think AVG(Marks) is for a given subject, so modified trigger definition accordingly.
declare a variable inside the trigger and assign it with the subquery
declare avg_mark integer default 0;
set avg_mark := (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID);
then use the variable "avg_mark" in your update statement...
it may work...
if not then check the delimiter just below phpmyadmin sql box . It should be "$$"

Categories