Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 update or insert in a trigger

Author  Topic 

ferrethouse
Constraint Violating Yak Guru

352 Posts

Posted - 2011-12-07 : 18:30:38
My brain fog is particularly bad today.

I have a trigger on table Activity. I want to update or insert into ActivitySummary from the trigger on the activity table. What is the most efficient way check if a record exists and therefore update else do an insert. I would have thought something like this...

set @check = select activityid from activitysummary where studentsid = inserted.studentsid

But that doesn't work if many records were inserted. I can only think of cursors and I know they are evil.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-12-07 : 18:48:38
if exists (select * from activitysummary a join inserted i on a.studentsid = i.studentsid)
...
else
...

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-08 : 01:03:26
isnt it just of matter of using inner join to check if records exists and do update

for inserts you can check using a left join and looking for null conditions

if sql 2008, you can combine both using a MERGE

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -