I'm a T-SQL coder and I'm starting to code in MySQL Workbench.
I'm trying to apply triggers and function in MySQL but am having difficulties with the syntax.
Basically my code below wants to use the StudentID (incrementing) as basis for my Studentnumber code
having max value of 5 zero digits. liek this----> 13-00001 (where 13 is the last digit of the year and 1 is the StudentID value.) So if I insert 291 records, my last record will be 13-00291.
In T-SQL I have the following code:
create table Student
( StudentID int identity not null primary key,
Name varchar(100),
StudentNumber varchar(10)
)
create function StudentNumber (#id int)
returns char(9)
as
begin
return (SELECT SUBSTRING((CONVERT(VARCHAR(10),GETDATE(),112)),3,2)) + '-' + right('000000' + convert(varchar(10), #id), 6)
end
create trigger Student_insert on Student
after insert as
update
Student
set
Student.StudentNumber = dbo.StudentNumber(Student.StudentID)
from
Student
inner join
inserted on Student.StudentID= inserted.StudentID
When I started coding in MySQL creating tables is basic, but when I created my triggers and function,
it seems there is a big difference with how mysql works.
I've read that Identity's equivalent in MYSQL is AutoIncrement PK,
but I've also read that when a trigger is fired, it can't get the value of my PK because the record hasnt been committed yet (or something along those lines) I've read that the only way to do the function I want in MySQL is to create a temp table which will store the ID or something. But I'd like to ask the opinion of others here if there's a way to recreate my function in MYSQL without having to resort to creating temp tables.
Thanks
If you want to use an auto_increment field for this in MySql you'll have to have a separate table for sequencing like this.
Your schema
CREATE TABLE student_seq(id INT AUTO_INCREMENT NOT NULL PRIMARY KEY)|
CREATE TABLE student
( StudentID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100),
StudentNumber VARCHAR(8) DEFAULT NULL
);
Function
CREATE FUNCTION student_number (id INT)
RETURNS VARCHAR(8)
RETURN CONCAT(DATE_FORMAT(CURDATE(), '%y'), '-', LPAD(id, 5, '0'));
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_student_insert
BEFORE INSERT ON Student
FOR EACH ROW
BEGIN
DECLARE nextid INT DEFAULT 0;
INSERT INTO student_seq VALUES(NULL);
SET nextid = LAST_INSERT_ID();
SET NEW.studentid = nextid, NEW.studentnumber = student_number(nextid);
END$$
DELIMITER ;
Lets insert a new student
INSERT INTO student (studentid, name) VALUES(0, 'Jhon');
You'll get in student table
| STUDENTID | NAME | STUDENTNUMBER |
------------------------------------
| 1 | Jhon | 13-00001 |
Here is SQLFiddle demo.
Related
I am trying to understand triggers in MySQL, but am having a few problems.
I'm trying to implement a trigger which on every UPDATE/INSERT in the table Grades it updates the column "gpa" in another table called Student, but cannot do it properly.
Code:
CREATE TABLE Student
(
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
age TINYINT,
gpa NUMERIC(3, 2) DEFAULT 2
);
CREATE TABLE Grades
(
StudentId INT PRIMARY KEY,
grade_bg INT,
grade_math INT,
grade_subd INT,
FOREIGN KEY(StudentId) references Student(Id)
);
delimiter |
CREATE TRIGGER update_gpa
AFTER INSERT
ON Grades
FOR EACH ROW
BEGIN
UPDATE Student SET gpa = ((grade_bg + grade_math + grade_subd)/3) WHERE StudentId = Id;
END;
|
After this when I try to insert in the table Student I get:
"Error 1054: Unknown column 'StudentId' in where clause".
For example:
INSERT INTO Student(name, age)
VALUES ('Joshua', 17);
Also when I try writing "AFTER INSERT, UPDATE" I get a syntax error from the MySQL Workbench and don't know how to make the trigger activate on INSERT AND UPDATE in the table Grades.
Any help is appreciated! Thanks in advance!
I don't know much about Triggers but I tried just running the update statement and noticed you hadn't defined the join:-
UPDATE Student
INNER JOIN Grades ON Grades.StudentId = Student.Id
SET Student.gpa = ((Grades.grade_bg + Grades.grade_math + Grades.grade_subd)/3);
Hello i have this problem:
I have 2 tables :
Create table Student(
Num int Auto_increment,
Name varchar(100),
Age int,
Gpa int default 2,
primary key(Num)
);
Create table Grades(
Num int,
Grade_BG int default 2,
Grade_Math int default 2,
Grade_SUBD int default 2,
Primary key (Num)
);
And i want to make a trigger to update the GPA with the three grades from the other table but i'm having hard time doing it.
Your trigger code :-
create trigger stud_marks after INSERT on Grades
for each row
update Student
set Gpa = (Grades.Grade_BG+Grades.Grade_Math+Grades.Grade_SUBD)/3;
The for each row means for each row inserted to grades so the grades. qualifier is unnecessary and should be replaced with NEW. 'Within the trigger body, the OLD and NEW keywords enable you to access columns in the rows affected by a trigger.' - https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
Also the update needs to know which student to update so a where clause would be useful
so
create trigger stud_marks after INSERT on Grades
for each row
update Student
set Gpa = (new.Grade_BG+new.Grade_Math+new.Grade_SUBD)/3
where student.num = new.num;
Assuming num in grades actually relates to num in student. If not then you need to create a relationship.
You may also need to create UPDATE and DELETE triggers.
Hey all so I have created a table named products that looks like so:
`CREATE TABLE products
(
Prod_ID int(10),
Prod_name varchar(20),
Prod_qty varchar(20),
Prod_price int(20)
);`
Product_log table is nearly identical to another table called products:
`CREATE TABLE product_log
(
Prod_ID int(10),
Prod_name varchar(20),
Action_Date date,
Updated_by varchar(30),
Action varchar(30)
);`
Next I have created a trigger called products_after_insert which should insert data into the product_log table after a row in products is inserted.
The requirement for after insert trigger is that action date should be inserted in the product_log table and the user name should be inserted like who inserted the data ex: data operator,
and on last the action should be inserted in the product_log table automatically like action here is insertion.
here is my trigger:
`DELIMITER //
CREATE TRIGGER products_after_insert
AFTER INSERT
ON products
FOR EACH ROW
BEGIN
DECLARE data_operator int(10);
DECLARE action_per varchar(200);
SET data_operator = 1;
SET action_per = 'INSERTION';
IF data_operator=1 THEN
INSERT INTO product_log(prod_id,prod_name,Action_date,Updated_by,Action)
VALUES(NEW.prod_id,NEW.prod_name,SYSDATE(),'data_operator','action_per');
END IF;
END;
//DELIMITER;`
Now, I assume I am constructing my trigger incorrectly because it appears to not be working.
Does anyone know what I am doing wrong? Any help would be greatly appreciated! Thanks!
There's at least this you are doing wrong :
VALUES(NEW.prod_id,NEW.prod_name,SYSDATE(),'data_operator','action_per');
You have properly defined the variables data_operator and action_per previously:
SET data_operator = 1;
SET action_per = 'INSERTION';
But in your INSERT instruction you surrounded them with quotes, which turned them into strings. Your instruction should be :
VALUES(NEW.prod_id,NEW.prod_name,SYSDATE(),data_operator,action_per);
I have a table called test like this:
CREATE TABLE test(
id int auto_increment primary key,
prefix varchar(1) not null default ('s'),
newid varchar(10) null);
I would like column newid to be combined values of column id and column prefix when inserting new values into table test. For example:
id prefix newid
1 s s1
2 s s2
...
So i tried to create after insert trigger like this:
DELIMITER $$
CREATE TRIGGER test
AFTER INSERT ON test
for each row BEGIN
set newid = concat(id,prefix);
END$$
DELIMITER ;
But i got this error:
#1193 - Unknown system variable 'newid'
Please tell me what I need to fix to achieve the result needed.
Best Regards
I'm trying to export data from a multivalue database (Unidata) into MySQL. Lets say my source data was a person's ID number, their first name and all the states they've lived in. The states field is a multi value field and I'm exporting them so that the different values within that field are seperated by a ~. A sample extract looks like:
"1234","Sally","NY~NJ~CT"
"1235","Dave","ME~MA~FL"
"3245","Fred","UT~CA"
"2344","Sue","OR"
I've loaded this data into a staging table
Table:staging
Column 1: personId
Column 2: name
Column 3: states
What I want to do is split this data out into two tables using a procedure: a persons table and a states table. A person can have many entries in the states table:
Table 1: persons
Column 1: id
Column 2: name
Table 2: states
Column 1: personId
Column 2: state
My procedure takes the data from the staging table and dumps it over to table 1 just fine. However, i'm a little lost how how to split the data up and send it to table 2. Sally would need to have three entries in the states table (NY, NJ, CT), Dave would have 3, Fred would have 2 and Sue would have1 (OR). Any ideas on how to accomplish this?
try something like this : http://pastie.org/1213943
-- TABLES
drop table if exists staging;
create table staging
(
person_id int unsigned not null primary key,
name varchar(255) not null,
states_csv varchar(1024)
)
engine=innodb;
drop table if exists persons;
create table persons
(
person_id int unsigned not null primary key,
name varchar(255) not null
)
engine=innodb;
drop table if exists states;
create table states
(
state_id tinyint unsigned not null auto_increment primary key, -- i want a nice new integer based PK
state_code varchar(3) not null unique, -- original state code from staging
name varchar(255) null
)
engine=innodb;
/*
you might want to make the person_states primary key (person_id, state_id) depending on
your queries as this is currently optimised for queries like - select all the people from NY
*/
drop table if exists person_states;
create table person_states
(
state_id tinyint unsigned not null,
person_id int unsigned not null,
primary key(state_id, person_id),
key (person_id)
)
engine=innodb;
-- STORED PROCEDURES
drop procedure if exists load_staging_data;
delimiter #
create procedure load_staging_data()
proc_main:begin
truncate table staging;
-- assume this is done by load data infile...
set autocommit = 0;
insert into staging values
(1234,'Sally','NY~NJ~CT'),
(1235,'Dave','ME~MA~FL'),
(3245,'Fred','UT~CA'),
(2344,'Sue','OR'),
(5555,'f00','OR~NY');
commit;
end proc_main #
delimiter ;
drop procedure if exists cleanse_map_staging_data;
delimiter #
create procedure cleanse_map_staging_data()
proc_main:begin
declare v_cursor_done tinyint unsigned default 0;
-- watch out for variable names that have the same names as fields !!
declare v_person_id int unsigned;
declare v_states_csv varchar(1024);
declare v_state_code varchar(3);
declare v_state_id tinyint unsigned;
declare v_states_done tinyint unsigned;
declare v_states_idx int unsigned;
declare v_staging_cur cursor for select person_id, states_csv from staging order by person_id;
declare continue handler for not found set v_cursor_done = 1;
-- do the person data
set autocommit = 0;
insert ignore into persons (person_id, name)
select person_id, name from staging order by person_id;
commit;
-- ok now we have to use the cursor !!
set autocommit = 0;
open v_staging_cur;
repeat
fetch v_staging_cur into v_person_id, v_states_csv;
-- clean up the data (for example)
set v_states_csv = upper(trim(v_states_csv));
-- split the out the v_states_csv and insert
set v_states_done = 0;
set v_states_idx = 1;
while not v_states_done do
set v_state_code = substring(v_states_csv, v_states_idx,
if(locate('~', v_states_csv, v_states_idx) > 0,
locate('~', v_states_csv, v_states_idx) - v_states_idx,
length(v_states_csv)));
set v_state_code = trim(v_state_code);
if length(v_state_code) > 0 then
set v_states_idx = v_states_idx + length(v_state_code) + 1;
-- add the state if it doesnt already exist
insert ignore into states (state_code) values (v_state_code);
select state_id into v_state_id from states where state_code = v_state_code;
-- add the person state
insert ignore into person_states (state_id, person_id) values (v_state_id, v_person_id);
else
set v_states_done = 1;
end if;
end while;
until v_cursor_done end repeat;
close v_staging_cur;
commit;
end proc_main #
delimiter ;
-- TESTING
call load_staging_data();
select * from staging;
call cleanse_map_staging_data();
select * from states order by state_id;
select * from persons order by person_id;
select * from person_states order by state_id, person_id;