简体   繁体   中英

SQL Insert Trigger - Update other record

I'm working on a small database in SQL Server 2008 to track employee changes. I'm having trouble with an Insert Trigger at the moment. What I want to happen, is that when a "Record" is inserted into the Record table, it finds the previous open record (ie one without an end date) for that Employee (EmpID), if there is one, and updates it with an EndDate - which will be calculated as the day before the inserted StartDate. Here is what I have tried, to no success:

CREATE TRIGGER [dbo].[trgInsertRecord] ON [dbo].[Record]
FOR INSERT
AS

declare @EmpID int;
declare @StartDate date;
declare @EndDate date;

select @EmpID=i.EmpID from inserted i;
select @StartDate=i.RealStart from inserted i;
set @EndDate=DATEADD(DAY,-1,@StartDate)

UPDATE Record
SET RealEnd=@EndDate
WHERE EmpID=@EmpID AND RealEnd=NULL;

Can somebody please help me understand my mistake?

Assuming only a single row exists for a given EmpID and NULL RealEnd, you can join to the inserted table for the update operation like the example below. The best practice is to code triggers as to handle multiple rows updated by a single statement so you should avoid local scalar subqueries in triggers.

CREATE TRIGGER [dbo].[trgInsertRecord] ON [dbo].[Record]
FOR INSERT
AS

UPDATE r
SET RealEnd = DATEADD(DAY, -1, i.RealStart)
FROM Record AS r
JOIN inserted AS i ON
    r.EmpID=i.EmpID
    AND RealEnd IS NULL;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM