1

i have simple question regarding Triggers in sql.

I am completely new and i do not know how to handle it.

I have one table myshift with shiftid, starttime stoptime and lastupdate.

create trigger ShiftTriggerr on myshift for update as 
if update(stoptime)
update myshift set lastupdated = getdate() 

what i want is when stoptime will update, the lastupdate field will update with getdate().

but when i run this it does not update one row but updated all rows. I do not know how to apply check on this trigger

2 Answers 2

2

You need to use the INSERTED virtual table:

CREATE TRIGGER dbo.ShiftTriggerr 
ON dbo.myshift AFTER UPDATE
AS
BEGIN
     SET NOCOUNT ON;
     IF UPDATE(stoptime)
     BEGIN
         UPDATE A
         SET lastupdated = getdate() 
         FROM dbo.myshift A
         INNER JOIN INSERTED B
             ON A.shiftid = B.shiftid
     END
END
Sign up to request clarification or add additional context in comments.

Comments

0

myshift should have a primary key defined, if that is shiftId, then,

  create trigger ShiftTriggerr on myshift for update as        
     update m
        set lastupdated = getdate() 
     From myshift m Join inserted i 
        on i.shiftId = m.shiftId 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.