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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.