I need to write an SQL trigger to insert the date into a row of another table after an insert.
The data comes in as such:
A form is submitted to _OnsiteTable which includes a JobID, this JobID matches a current entry containing a JobID value in _JobTable. Upon insert of the data into _OnsiteTable I need a trigger that will insert the current date into a column called JobClosedDate in JobTable.
It needs to insert the date into the row that matches the JobID value entered in the form on _OnsiteTable.
I have this so far but I don't know how to compare the JobID values between tables and insert into the specific row.
CREATE TRIGGER UpdateClosedDate
AFTER INSERT on _OnsiteTable
BEGIN
Declare ClosedDate DATETIME;
SET ClosedDate = CURDATE();
CASE WHEN (ClosedDate) = ?
THEN INSERT INTO `_JobTable`( `JobClosedDate`)
VALUES
( ClosedDate);
END CASE;
END
Any help is greatly appreciated!
Complete query now working, thank you! As below:
CREATE TRIGGER UpdateClosedDate
AFTER INSERT on _OnsiteTable
BEGIN
Declare ClosedDate DATETIME;
SET ClosedDate = CURDATE();
UPDATE `_JobTable` SET `JobClosedDate` = ClosedDate WHERE `JobID` = new.JobID;
END
Since the problem was solved with the given comment I will add it here to reference for others with similar issues:
Since you want to Update a column ("insert a value into a column...") You just need to fix your trigger changing your current case statement to an update command as follow:
UPDATE `_JobTable`
SET `JobClosedDate` = ClosedDate
WHERE `JobID` = NEW.JobID;
Related
I have these two tables
**Table tb_data**
tb_id
timestamp
pagid
proid
status
(and many more)
**Table tb_units**
pag_id
pag_sn
user
latest_profile
latest_status
latest_feedback
latest_timestamp
Whenever a new row is created in tb_data, i would like some values updated in tb_units. In tb_units pag_id is unique and every number only exists once.
How do I trigger this, so the new values in tb_data are updated in tb_units? pagid equals pag_id and the corresponding values proid should update latest_profil, status should update latest_status, timestamp should update latest_timestamp
In the end I would like to end up with the latest pagid input to tb_data to be available in tb_units, since tb_data will contain multiple rows from the same pagid
I hvae tried several different aproaches, and have read a lot of examples, but I just don't get how these triggers work!
Latest example, that doesn't work:
CREATE TRIGGER update_units
AFTER INSERT ON tb_data
BEGIN
UPDATE tb_units
SET latest_profile = tb_data.9C,
latest_status = tb_data.91
WHERE pag_id = tb_data.86;
END
Not sure but something like this should work
CREATE TRIGGER update_units
AFTER INSERT ON tb_data
BEGIN
UPDATE tb_units
SET latest_profile = new.proid,
latest_status = new.status
WHERE pag_id = new.pagid;
END
suppose for the table student if insert query is executed as INSERT INTO student(id,name) VALUES (1,'sumit');.Just after insertion of the row I want the recently inserted row's name field value to be capitalised using trigger.I searched for it every where but couldn't get working code,please some body help?
You can write the after insert and update trigger on table.
CREATE TRIGGER lcase_insert BEFORE INSERT ON my_table FOR EACH ROW
SET NEW.name = LOWER(NEW.name);
CREATE TRIGGER lcase_update BEFORE UPDATE ON my_table FOR EACH ROW
SET NEW.name = LOWER(NEW.name);
here NEW.name is your name inserted in table.
I have an employee table (em) that contains, among other things, a floor Id (fl_id) and room Id (rm_id). In certain circumstances (when em_loc_cnt = 0) I want to set the em record's fl_id and rm_id to null. Below is my code so far.
I am not sure how to refer to the fl_id & rm_id in the commented line. Will I run into issues because this trigger is being called as a result of the em record being updated and I am updating that same record in the trigger?
Suggestions?
IF EXISTS (SELECT * FROM [sysobjects] WHERE [name] = 'em_upd_self_serv_t' AND [type] = 'TR')
BEGIN
DROP TRIGGER [dbo].[em_upd_self_serv_t]
END
GO
CREATE TRIGGER [dbo].[em_upd_self_serv_t]
ON [dbo].[em]
AFTER UPDATE
AS
BEGIN
DECLARE #em_id VARCHAR(35),
#em_loc_cnt INT;
SET #em_id = (SELECT em_id FROM inserted);
SET #em_loc_cnt = (SELECT COUNT(*) FROM emlocs WHERE em_id = #em_id);
IF (#em_loc_cnt = 0)
BEGIN
-- I want to set the fl_id and the rm_id to NULL
END
END;
Your fundamental flaw is that you seem to expect the trigger to be fired once per row - this is NOT the case in SQL Server. Instead, the trigger fires once per statement, and the pseudo table Inserted might contain multiple rows.
Given that that table might contain multiple rows - which one do you expect will be selected here??
SET #em_id = (SELECT em_id FROM inserted);
It's undefined - you might get the values from arbitrary rows in Inserted.
You need to rewrite your entire trigger with the knowledge the Inserted WILL contain multiple rows! You need to work with set-based operations - don't expect just a single row in Inserted !
You need to change your code to something like this:
IF EXISTS (SELECT * FROM sys.triggers WHERE [name] = 'em_upd_self_serv_t')
DROP TRIGGER [dbo].[em_upd_self_serv_t]
GO
CREATE TRIGGER [dbo].[em_upd_self_serv_t]
ON [dbo].[em]
AFTER UPDATE
AS
UPDATE dbo.em
SET fl_id = NULL, rm_id = NULL
FROM Inserted i
WHERE em_id = i.em_id
AND NOT EXISTS (SELECT * FROM dbo.emlocs WHERE em_id = i.em_id)
I Have a trigger that takes the old values from the orginal tabel and put these values in one cell on another table except the date and user, when any updates occurs, the orginal table has attributes which is null when the raw is inserted like (updatedate and updateuser), so when this raw is updated those two attributes will be update to the current date and user who did the update, so the trigger should get those two parameters when they are null should get the inserted values and when they are not null should get the new values,however the trigger's syntax is correct but the result is incorrect
ALTER Trigger [dbo].[OrdersUpdate] on [dbo].[Orders]
After Update
as
Declare #UpdateDate datetime, #UpdateUser uniqueidentifier
Set #UpdateDate=(Select UpdateDate from deleted)
Set #UpdateUser=(Select UpdateUser from deleted)
If #UpdateDate is null
Begin
Set #UpdateDate=(select UpdateDate from inserted)
End
Else
Set #UpdateDate=(select UpdateDate from deleted)
If #UpdateUser is null
Begin
Set #UpdateUser=(select UpdateUser from inserted)
End
Else
Set #UpdateUser=(select UpdateUser from deleted)
Insert Into UpdateRows
Select 'Orders', id,#UpdateDate,#UpdateUser,
convert(nvarchar,InvoiceID,1)+'_'+
convert(nvarchar,OrderID,1)+'_'+
MatterName+'_'+
convert(nvarchar,PrintID,1)+'_'+
OrderName+'_'+
CONVERT(nvarchar,lenght,1)+'_'+
CONVERT(nvarchar,Wide,1)+'_'+
CONVERT(nvarchar,Quantity,1)+'_'+
CONVERT(nvarchar,EnterDate,101)+'_'+
CONVERT(nvarchar,EndDate,101)
From deleted
thanks HLGEM
First, you never ever write a sql server trigger where you set the values of a scalar parameter to something from inserted or deleted. These tables can contain multiple rows. The trigger must account for that. โ HLGEM
how can i create a trigger function before adding/updating,the function should check records that have the same id (i.e comparison by id with existing objects that have the same property as the temporary_object)If a record with the id is found, then that entry is set to the time_dead, and then it adds an entry containing the corresponding values โโof the attributes found in that record (except those that are set for a new record), when time_dead is empty then time_create of a new time is equal to that time at the current moment . Thus,a new record time_create is like the time_dead's ancestor.
If a record with that id is found then it is added to the database with the establishment as the time_create of the current time.
for example here is a simple explanation(just for explanation purposes)
id time_create time-dead student amount
1 06.12 07.12 henry 500
1 07.12 henry 1000
so if a student called henry with id 1 entered a room at 06.12 and left at 07.12 the next time he enters another room again time_dead will be equal to time_create(so time_dead of old entry and time_create of new entry - will be equal)
these are my tables below in sql format
CREATE TABLE temporary_object
(
id integer NOT NULL,
time_create timestamp without time zone NOT NULL,
time_dead timestamp without time zone,
CONSTRAINT temporary_object_pkey PRIMARY KEY (id, time_create)
)
CREATE TABLE persons
(
fname text,
fsurname text,
)
INHERITS (temporary_object)
CREATE TABLE rooms
(
roomnum integer,
course integer,
passport text,
students_number text
)
INHERITS (temporary_object)
this is what i am trying to do but im afraid i do not know how to finish it but im 100% not right may some help out
CREATE TRIGGER trigger2
BEFORE INSERT OR UPDATE
ON persons
FOR EACH ROW
EXECUTE PROCEDURE func1();
and this is the function
CREATE OR REPLACE FUNCTION func1() RETURNS TRIGGER AS $persons$
DECLARE
time_create integer;
time_dead timestamp;
id timestamp;
BEGIN
IF (TG_OP = 'INSERT') THEN
time_create=
I can't tell you what I'm missing from your question, but I try to answer what I think I understood.
Row level triggers can access the version of the row affected with the NEW and OLD variables (depending on TG_OP). In this case, you can use NEW:
CREATE OR REPLACE FUNCTION func1()
RETURNS TRIGGER AS
$persons$
DECLARE
i integer;
BEGIN
IF TG_OP = 'INSERT'
THEN
UPDATE persons
SET time_dead = NEW.time_create
WHERE
id = NEW.id -- we are looking for the same ID
AND time_dead IS NULL
;
ELSE -- UPDATE
-- do here something
END IF;
END;
$persons$
LANGUAGE plpgsql;
This is only a starter, modify it to your needs.