MySQL trigger - Trigger table name interpreted as field - mysql

I am having an issue with a trigger I have put in a database I am building. It is the only trigger in the database. Here are the two tables being used.
Client Table
create table client (
clientNum INT(5) not null auto_increment,
clientName TEXT(30) not null,
clientEmail VARCHAR(64) not null,
clientGender CHAR(1) not null,
clientDOB DATE not null,
clientAddress TEXT(50),
clientPhone VARCHAR(12) not null,
hasInsurance CHAR(1) not null,
clientBalanceOwed DECIMAL(10,2),
clientLastDateVisited DATE,
clientNextVisitDate DATE,
primary key (clientNum));
Insurance Table
create table insurance(
insuranceNum INT(5) not null auto_increment,
cardNum INT(16),
policyNum INT(6),
policyHolder TEXT(30),
clientNum INT(5),
primary key (insuranceNum),
foreign key (clientNum) references client(clientNum));
The idea for the following trigger is to only create an insurance row when a client is added to the database that has the 'hasInsurance' field set to 'y'. Then, once that client has been added, create a new insurance row with the clientNum set to the clientNum that was just added.
The Trigger
delimiter $$
create trigger New_Insurance_Row after insert on client
for each row
begin
if(client.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
end$$
Everything up to this point works as intended, until you try to insert a new client into the table and call the trigger. Once I try and add the following line of code:
The Insert Statement
insert into client(clientName, clientEmail, clientGender, clientDOB,
clientAddress,
clientPhone, hasInsurance, clientBalanceOwed, clientLastDateVisited,
clientNextVisitDate)
values
('Darcy Watts','dwatts#email.com','m','1996-5-9','Belfast, Charlottetown
PEI','123-222-3333','y','400.77','2017-8-12','2019-9-6');
When I try and run this I am met with this error:
#1109 - Unknown table 'client' in field list
So from what I've learned over the last few hours is that this error usually happens when you put the '`' (backtick) on a variable or table name, MySQL thinks that entry is part of a field list or something along that line. So I changed the trigger to just be 'client' by itself and I still got an error. Dropped the old database and everything. One more thing, the insert statement does work by itself if the trigger has not been entered yet.
Any help would be appreciated! Thanks!

I guess your hasInsurance should be from the new record.
...
if(new.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
...
--
DB Fiddle (provided by GMB)

Related

NULL value when insering row with trigger SQL and CONCAT function

I put 10,000 avatar photos on a server and I would like for each row inserted into the 'studenttable' table, the 'photo' column to be the concatenation of the url of the folder of my photos + the id of the inserted student.
However, the CONCAT function returns a NULL value with the basic trigger used.
First, here is the above mentioned table :
CREATE TABLE `studenttable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`gender` enum('Male','Female','Other') NOT NULL,
`email` varchar(100) DEFAULT NULL,
`birthDate` date DEFAULT NULL,
`photo` varchar(535) DEFAULT NULL,
`mark` double DEFAULT NULL,
`comment` varchar(535) DEFAULT NULL,
PRIMARY KEY (`id`)
)
and here is the basic trigger I created:
DELIMITER $$
create trigger IMAGE_LienApi
before insert on studenttable
for each row
begin
set NEW.photo = CONCAT('https://url-of-folder-with-my-images/',NEW.id,'.png');
end$$
DELIMITER ;
For information, the images are referenced in this way:
number.png
So when I insert a new student with this trigger, the photo column is always set to NULL.
The problem must come from NEW.id, because when I replace this value with a string, it works.
I also tried with
NEW.photo = 'https://url-of-folder-with-my-images/' + CONVERT(VARCHAR(5),NEW.id),'.png';
but it did not work
Thank you in advance for your help and if someone could explain to me especially why the CONCAT does not work, that would be great !
CONCAT() returns NULL if any of its arguments are NULL.
In a BEFORE INSERT trigger, the NEW.id value is NULL. It hasn't been generated yet.
But in an AFTER INSERT trigger, it's too late to change the NEW.photo column of your row. You can't change columns in an AFTER trigger.
You cannot make a BEFORE INSERT trigger to concatenate an auto-increment value with other columns. The best you can do is let the INSERT complete, and then subsequently do an UPDATE to change your photo column.
The alternative is to forget about using the builtin AUTO_INCREMENT to generate id values, instead generate them some other way and specify the value in your INSERT statement.

Error 2014 MySQL. Commands out of sync, when i create my first trigger

I am creating a database of information about application stores and well, I wanted to venture to create my first trigger, but something in my syntax fails (I am new to programming) and the terminal returns the 2014 error commands out of sync.
I put you in context: I have created 2 tables, 'Empleados'(employees) and 'Empresas'(company), with relation N: N, this has created another table of the relationship between these entities which is 'TRABAJAN'(work), there, I've put the Start Date (Fecha_inicio) in the company and the End Date(Fecha_fin), and also, I've put another column with boolean values on whether they are working or not. When I inserted the data I allowed that if they continued working, they had a NULL value.
Well, what I want is to create a trigger that when modifying the status of the working column from 1 to 0, I modify the NULL value of the Date_fin column by the value of the current system date.
I leave you the code and the trigger attempt I made:
CREATE DATABASE Info_Tiendas_App2;
USE Info_Tiendas_App2;
CREATE TABLE Empleados (
codEmpleado SMALLINT PRIMARY KEY,
DNI VARCHAR(9) NOT NULL UNIQUE,
NomEmpleado VARCHAR(40) NOT NULL,
Calle VARCHAR(30),
Numero NUMERIC(3,0),
CodPostal NUMERIC(5,0),
CorreoElect VARCHAR(50)
);
CREATE TABLE Empresas (
codEmpresa SMALLINT PRIMARY KEY,
NomEmpresa VARCHAR(50) NOT NULL,
PaisFacturacion VARCHAR(15) NOT NULL,
AnnoCreacion NUMERIC(4,0),
Correo VARCHAR(50),
PagWeb VARCHAR(40)
);
CREATE TABLE TRABAJAN (
codEmpleado SMALLINT,
codEmpresa SMALLINT,
Fecha_inicio DATE,
Fecha_fin DATE,
Trabajando BOOLEAN,
PRIMARY KEY (codEmpleado, codEmpresa),
FOREIGN KEY (codEmpleado) REFERENCES Empleados(codEmpleado)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (codEmpresa) REFERENCES Empresas(codEmpresa)
ON DELETE CASCADE
ON UPDATE CASCADE
);
-- AquĆ­ el trigger
DROP TRIGGER IF EXISTS Mod_fecha_fin;
CREATE TRIGGER Mod_fecha_fin
AFTER UPDATE
ON TRABAJAN
FOR EACH ROW
BEGIN
IF TRABAJAN(Trabajando) = 0
UPDATE INTO TRABAJAN(Fecha_fin) SET Fecha_fin = (NOW())
ELSE
SET Fecha_fin = NULL
END //
Why do I get that error? What would I have to modify ?, and one last query, is the trigger well designed?
Thank you very much everyone for your help and time, greetings
As an alternative approach that avoids triggers; consider using a calculated/derived column: https://dev.mysql.com/doc/refman/8.0/en/create-table-generated-columns.html
CREATE TABLE TRABAJAN (
codEmpleado SMALLINT
, codEmpresa SMALLINT
, Fecha_inicio DATE
, Fecha_fin DATE
, Trabajando BOOLEAN AS (CASE WHEN Fecha_fin IS NULL THEN b'1' ELSE b'0' END),
);
When Fecha_fin is NULL, the value of Trabajando is set to true (b'1').
When Fecha_fin is NOT NULL, the value of Trabajando is set to false (b'0').
i.e. when there's an end date set, they are considered to not be working. If there's no end date, they are considered to be working.
All you then have to do is update the value of Fecha_fin e.g.:
UPDATE TRABAJAN
SET Fecha_fin = CURRENT_TIMESTAMP
WHERE codEmpleado = 937
AND codEmpresa = 123
AND Fecha_fin IS NULL
;

MYSQL - How to insert data to another server DB table

I am trying to insert data to Second server's DB table after inserted to First server' table like below structure,
Second server :
use SecondServerDB;
CREATE TABLE user (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB;
After created table in Second sever, I have created table in First server like below,
First server :
use FirstServerDB;
CREATE TABLE remote_user2 (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=FEDERATED
DEFAULT CHARSET=latin1
CONNECTION='mysql://MysqlUserName:MysqlUserPassword#SecondServer.MyDomain.com:3306/SecondServerDB/user';
After created FEDERATED table in second server, Created triggers in same server like below,
DELIMITER $$
CREATE TRIGGER remote_insert_Testing AFTER INSERT ON remote_user2 FOR EACH ROW
BEGIN
INSERT INTO user (ID,name, age) VALUES (NEW.ID,NEW.name, NEW.Age);
END $$
DELIMITER ;
If i run insert query like below,
INSERT INTO remote_user2 (ID,name, age) VALUES (1,'Name',27);
Then it shows, Error Code: 1146. Table 'FirstServerDB.user' doesn't exist.
where am i doing mistake?
Note : I googled and found out What i am trying is possible. How to create trigger to insert data to a database on another server for possible
Try using the fully qualified table names in your trigger:
DELIMITER $$
CREATE TRIGGER remote_insert_Testing
AFTER INSERT ON FirstServerDB.remote_user2 FOR EACH ROW
BEGIN
INSERT INTO SecondServerDB.user (ID,name, age)
VALUES (NEW.ID, NEW.name, NEW.Age);
END $$
DELIMITER ;
If you don't mind moving the data through a normal query, you can try the following:
INSERT INTO SecondServerDB.user (ID, name, age)
SELECT ID, name, age
FROM FirstServerDB.remote_user2

Is there a way to create a primary key and have it cascade into other tables without re-entering data into the new tables?

I am working on setting up a database and have created tables that cascade out like using the cascade on update for the foreign key. I have two tables being worked with to try to solve this. My tables are like this:
create table Item(Item int(4) not null, EquipName varchar(20), Equip int(4)
not null, primary key(Item, Equip))
create table Cross(Time timestamp default now(), Cross varchar(10) default
'null', Item int(4) not null, Equip int(4) not null, Stop varchar(20) default
'null', foreign key(Item, Equip) references Item(Item, Equip) on update
cascade);
So I want to be able to enter data into the Item table and have it be automatically put into Cross table where those values are cascaded to. This is why Cross and StopCount have a default value of null.
For example insert into Item values(5, fan, 4); I would like Cross to be populated in the FK spots automatically to what information was entered into Item.
You can use a trigger to autofill another table.
DELIMITER $$
CREATE TRIGGER init_cross AFTER INSERT ON item
FOR EACH ROW
BEGIN
INSERT INTO `cross`(item,equip) VALUES( NEW.item, NEW.equip );
END;
$$
DELIMITER ;

MySQL Error 1109 caused by Trigger

I have multiple tables in this database; two of which are involved with this trigger
create table shipment_item(
shipmentID int not null,
shipmentItemID int not null,
purchaseID int not null,
insuredValue decimal(5,2) not null,
constraint shipment_ItemPK primary key(shipmentID, shipmentItemID),
constraint shipmentFK foreign key(shipmentID)
references shipment(shipmentID)
on delete cascade,
constraint purchaseFK foreign key(purchaseID)
references purchase(purchaseID)
);
create table purchase(
purchaseID int not null auto_increment,
storeID int not null,
purchaseDate date not null,
description char(30) not null,
category char(30) not null,
price decimal(5,2) not null,
constraint purchasePK primary key(purchaseID),
constraint storeFK foreign key(storeID)
references store(storeID)
);
I'm trying to implement a trigger in my MySQL database. That trigger looks like this
DELIMITER //
CREATE TRIGGER checkInsuranceTrigger
BEFORE INSERT ON shipment_item
FOR EACH ROW BEGIN
IF(shipment_item.insuredValue <= purchase.price) THEN
SET NEW.insuredValue = purchase.price;
END IF;
END
//
DELIMITER ;
When I implement this trigger and then try to insert data into the shipment_item table I get the following error
Error Code 1109: Unknown Table 'shipment_item' in field list
Reference the column in the row being inserted with the NEW keyword, like you did on the SET statement.
To reference values from rows in other tables, you need a SQL statement, in your case, looks like you want a SELECT.
For example (following the outline of the logic in your trigger), something like this:
BEGIN
-- local variable
DECLARE ln_purchase_price DECIMAL(5,2);
-- populate local variable (this is just an example of one way to do this)
SELECT p.price
INTO ln_purchase_price
FROM purchase p
WHERE p.purchaseID = NEW.purchaseID
LIMIT 1;
-- compare value from row to local variable
IF (NEW.insuredValue <= ln_purchase_price) THEN
SET NEW.insuredValue = ln_purchase_price;
END IF;
May I suggest verifying that the table really exists in the same database as the trigger itself?