1. The update should be in the trigger there is no need for an additional procedure
2. The UPDATE statement will update every row in the JOURNAL table not just the ones updated
3. Triggers have a special table called INSERTED which contains the row(s) after any updates applied
NOTE that this table can have many rows
4. It is normal to join INSERTED to JOURNAL to apply any other updates
e.g.
ALTER TRIGGER [dbo].[tr_datediff] ON [dbo][JOURNAL] FOR INSERT,UPDATE
AS
UPDATE j
SET DIFF = CONCAT((DATEDIFF(Minute,start_date,[end_date])/60),':',
(DATEDIFF(Minute,start_date,[end_date])%60))
FROM INSERTED i
JOIN JOURNAL j ON j.key = i.key
Far away is close at hand in the images of elsewhere.
Anon.
Senchi - Monday, January 16, 2017 10:36 PM
Probably not. For a start, it's updating the whole table, not just the inserted/updated row(s). Second, is concatenating the minute portion of the start and end dates into the same column really helpful? The name of the column suggests to me that you want the number of minutes elapsed, in which case you should use the DATEDIFF function.
John
Edit - oops, ignore my "Second" point - I didn't read your code properly. Apologies.
Could you not just have the value as a computed column, then there is no need to update, as it's calculated? For example:USE DevTestDB;
GO
CREATE TABLE Dates (ID INT IDENTITY(1,1),
Start_Date DATETIME,
End_Date DATETIME,
DIFF AS (DATEDIFF(MINUTE,Start_date,End_Date)));
GO
INSERT INTO Dates (Start_Date, End_Date)
VALUES ('15-Jan-2016 19:19:19.000', '15-Jan-2016 20:20:20.000'),
('16-Jan-2016 10:10:00.000', '16-Jan-2016 16:45:22.000');
GO
SELECT *
FROM Dates;
UPDATE Dates
SET End_Date = '16-Jan-2016 12:17:22.000'
WHERE ID = 2;
SELECT *
FROM Dates;
GO
DROP TABLE Dates
This brings back the following respectively:ID Start_Date End_Date DIFF
----------- ----------------------- ----------------------- -----------
1 2016-01-15 19:19:19.000 2016-01-15 20:20:20.000 61
2 2016-01-16 10:10:00.000 2016-01-16 16:45:22.000 395
(2 row(s) affected)
ID Start_Date End_Date DIFF
----------- ----------------------- ----------------------- -----------
1 2016-01-15 19:19:19.000 2016-01-15 20:20:20.000 61
2 2016-01-16 10:10:00.000 2016-01-16 12:17:22.000 127
(2 row(s) affected)
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
I would follow David Burrows advice above. Join inserted to the original table in the trigger.
Viewing 15 posts - 1 through 15 (of 30 total)
You must be logged in to reply to this topic. Login to reply