Avatar of Sailing_12
Sailing_12
 asked on

SQL update trigger based on value

I need a trigger to do the following:

when deletionstatecode is set to 2 in table 'aaa', update statecode value to 1 in table 'bbb' where aaa.activityid = bbb.phonecallid
AAA
aaaid   deletionstatecode    activityid

--------------------------------------
BBB
bbbid   phonecallid   statecode

Open in new window

Microsoft SQL Server 2005Microsoft SQL Server

Avatar of undefined
Last Comment
Sailing_12

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
dportas

Do it in a stored procedure, not a trigger. Even better, consider changing the design so that there isn't a dependency between columns in two base tables. Maybe you could derive the same information in a view or query instead.
Scott Pletcher

A trigger is safer than a stored proc.  There is no guarantee that a stored proc will be used for all UPDATEs (and/or INSERTs).
Emes

CREATE TRIGGER TRIG2 ON AAA
For update
as

update BBB
set statecode = 1
 
 FROM inserted i
INNER JOIN bbb ON
BBB.phonecallid = i.activityid
and i.deletionstatecode = 2
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Sailing_12

ASKER
Scott, on your first inner join, I see alias b on phonecallid - but where is this defined?
Scott Pletcher

Sorry, should be bbb.
Scott Pletcher

I.e.:

INNER JOIN inserted i ON i.activityid = bbb.phonecallid
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Sailing_12

ASKER
OK thanks.
Sailing_12

ASKER
Thanks.