Hello I have some difficulties with simple trigger in MSSQL 2008.
I want to insert deleted row to another table.
Here is my trigger code:
use databasex;
GO
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, Function)
VALUES (deleted.Name, deleted.Surname, deleted.Function)
END
Employees table:
Name Surname Function ...
DeletedEmployees table:
Name Surname Function ...
I need somehow to specify that deleted columns are from deleted table, but how ?
I dont want to write subquery for every column.
How it being done ?
ps: is there any good tutorial on using triggers ? i believe i will need write more triggers in the future.
DELETED is a virtual table you select from (you may have deleted more than one row, so a single value is not enough)
Also, FUNCTION is a reserved word and needs to be escaped
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, [Function])
SELECT Name, Surname, [Function] FROM deleted
END
An SQLfiddle to test with.
Related
I'm learning mysql and i try to pass data from one table to another.
In Details, i have table1 with columns id, firstname, lastname etc.
Then i have a table2 with columns id, firstname, lastname, bodyfat, bodyweight, matchid.
The thing that i want is to pass the data firstname and lastname from table1 to table2 and they should be matched on table1.id = table2.matchid. Also the procedure should happen every time that new records are inserted into the table1, so the specific values are also updated and displayed in table2.
Is there any way to achieve that?
Thanks, in advance!
Use an after insert trigger:
DELIMITER //
CREATE TRIGGER after_user_insert
AFTER INSERT
ON table1 FOR EACH ROW
BEGIN
INSERT INTO table2 (firstname, lastname, matchid)
VALUES
(NEW.firstname, NEW.lastname, NEW.id);
END; //
DELIMITER ;
This assumes that you only want to insert new records in table2 with the first and last name, which is all the available information in table1. You could include other columns in the insert, but you would have to specify how to do that.
Beyond this, if you needed to initially populate table2 from table1, you could do an INSERT INTO ... SELECT:
INSERT INTO table2 (firstname, lastname)
SELECT firstname, lastname
FROM table1
-- WHERE <conditions>
you can use a trigger on table 1. A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
You can set a trigger on insert event in table 1. Here is a link https://dev.mysql.com/doc/refman/5.7/en/triggers.html that shows examples of trigger in mysql. Hope this helps
You can Create Trigger on Table1 with the insert or update statement into the Table2 using AFTER keyword, so that whenever a data is inserted in the Table 1 the trigger will be invoked and does the respective action based on your trigger definition.
For more details about how to create and use a trigger for MySQL refer the below link.
https://dev.mysql.com/doc/refman/5.7/en/triggers.html
The problem is I have class_id,faculty_id,course_id,semester,day and time records in class table. The class_id in this table is auto-incremented, faculty_id and course_id are also auto_incremented in there own respective tables.
My question is, when I insert values of semester, day and time I want the rest of the three ids(class_id,faculty_id and course_id) to be auto-incremented. I tried it with the help of triggers but it is not incrementing all the records together but it is incrementing one after the other.
Here are the queries used:
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin insert into class(faculty_id) values(new.faculty_id);
end
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT2 AFTER INSERT ON `course` FOR EACH ROW
begin insert into class(course_id) values(new.course_id);
end
I guess, you are mis interpreting the word "auto-increment" and its function with your current needs. From your two triggers i see you are trying to insert a new record into the tbl_class table when a new faculty/course is created.
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin
insert into class(faculty_id) values(new.faculty_id);
end
above code tells me after insert on tbl_faculty insert a new record in to the tbl_class with newly created faculty_id. There is no sign of course_id. of course it will show as blank/null if you don't set it.
the same applies for the other trigger.
I'm not sure if this thats is your intention but AFAIK this does not make any sense. The tbl_class should be created with existing faculty_id and course_id probably a drop-down-box in your form.
in case if you want to create new course or new faculty while creating a new class record. that is completely different question from what you are asking now. That would require a new form taking the new faculty name and perform an insert on the table and refresh the drop-down-box.
I am having the following issue:
I currently have 3 tables:
Person(personID, firstName, lastName, ...)
Household(householdID, personID, sons, daughters, ...)
Info(infoID, firstName, lastName, sons, daughters, ...)
The Info table is where all of the data is currently, while Person and Household are empty and I would like to distribute the data by putting the persons data into the Person table, and their household data into the Household table. Household.personID is a foreign key to Person.personID.
I am attempting to do this by inserting one row at a time into household, and after each row I will insert the persons data into the Person table (which will assign that person a unique personID) and then go back and insert that new personID into the household table.
After looking around I have found that I should either be using a transaction or a by creating a trigger (or both?). I do not know much about either but this is what I have created from what I have read:
CREATE TRIGGER PersonTrigger AFTER INSERT ON Person
FOR EACH ROW BEGIN
INSERT INTO Household
(personID, sons, daughters, ...")
VALUES (LAST_UPDATE_ID(), (SELECT sons, daughters, ...
FROM Info)
END;
INSERT INTO Person (firstName, lastName, ...)"
SELECT firstName, lastName, ...
FROM Info
But when attempting to run this I am getting the SQLException error
SQLException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EACH ROW BEGIN INSERT INTO TestHousehold(personID, givenName, lastName' at line 1
Any insight as to why this may be happening would be greatly appreciated. Thanks in advance.
Try using this:
CREATE TRIGGER distributing_info_details AFTER INSERT ON Info FOR EACH ROW
BEGIN
INSERT INTO Household (personID, sons, daughters, ...)
VALUES (new.PersonID, new.sons, new.daughters, ...)
# use ^ this key word to access the newly inserted ID.
INSERT INTO Person (firstName, lastName, ...)
VALUES (new.firstName, new.lastName,...)
END;
Please note that the two insert statements must be both between the BEGIN and END tags. And also note that I attached this trigger after insert on the Info table, not on Person because you said that all data are currently put on Info table.
You didn't tell us whether sons and daughter also refers to another person (which in that case, sons and daughters are foreign keys), and will yield to a different set of codes for this trigger.
I hope this helps.
I have two table:
Am using this query to populate my marks table with all 'id' in student table:
$module1= "insert into marks (stud_id,moduleID)
select sid, 1
from user_student
where sid not in (
select * from (
select distinct stud_id from marks where moduleID=1
) alias_name
)";
So i need to take all 'sid' from Table student and populate them into table marks my query above does all that. The problem am encountering is that every time i make a change to the data e.g column test1 , new record are inserted again.
If i populate the marks table manually, Can't i have a code that when new data is available in student table, the data is just updated in marks table...
I don't understand some points of your insert query, why insert sid in stud_id if there's a id in student table to relate them?
Maybe solve your problem the creation of a composed unique key to moduleID and stud_id and use a REPLACE in place of INSERT.
But the right way to do it is using a TRIGGER like:
DROP TRIGGER IF EXISTS `student_after_insert`;
CREATE TRIGGER `student_after_insert` AFTER INSERT ON `student`
FOR EACH ROW INSERT INTO marks (stud_id,moduleID)
SELECT NEW.`id`, `modules_table`.`id` FROM `modules_table`;
PS: I suppose you have a table of modules with name modules_table. Change it accordingly.
I haven't understand your question at the best, my tip is:
Make a unique constraint on marks table (up to you is the choice of best constraint rule).
Then use a trigger to make the right insert/update:
Something like that, (hope that syntax is right):
CREATE TRIGGER myTrigger
AFTER INSERT ON students
FOR EACH ROW
BEGIN
// check that insertion doesn't broke the constraint previously define, then
insert into marks (stud_id,moduleID) values (new.sid, 1);
END
Note: NEW is the row that you have as soon inserted/updated on students. Similar you have OLD metarow.
How can I create a trigger that will insert data into another table.
For example: I have a department table and a course table and the course table has a foreign key named department_id.
I insert CICCT into the course table but there is no CICCT in the department table.
My goal is to make the trigger add the value in the department table. How can I do this?
I tried this, is this correct?
CREATE TRIGGER department_insert BEFORE INSERT
ON course
FOR EACH row
begin
INSERT INTO department
(department_id,
description)
VALUES (new.id_dep,
NULL);
end;
Another question in the same subject, what do I need to do in order reduce the room capacity by one when a student enrolls?
Your trigger might look like this
CREATE TRIGGER department_insert
BEFORE INSERT ON course
FOR EACH ROW
INSERT IGNORE INTO department (department_id, description)
VALUES (NEW.id_dep, NULL);
Note:
to access column values of a row being inserted you have to use the NEW keyword
NEW.id_dep
^^^
use IGNORE clause in INSERT to ignore department_id values if they already exist in department table. It allows to greatly streamline your code.
Here is SQLFiddle demo
Make a separate post for your second question and specify table schemas