Avatar of rwheeler23
rwheeler23
Flag for United States of America asked on

What is the proper structure for an insert after SQL trigger?

This is my first attempt at an INSERT AFTER trigger. What I need to happen is if the transactions are coming from timesheets(SOURDOC='PATS') I need to replace the employee ID(ORMSTRID) with another value that is held in a user defined field on the employee card(UPR00100). In the GL20000 table the jrnentry field is the primary key. This trigger appears to work but do I need to add anything to it for data validation?

create trigger [dbo].[ORMSTRID] on [dbo].[GL20000] after insert
as
begin


UPDATE dbo.GL20000
      SET ORMSTRID=T2.USERDEF1
      FROM dbo.GL20000 T1
      INNER JOIN dbo.UPR00100 T2 ON T1.ORMSTRID=T2.EMPLOYID
      INNER JOIN inserted ins on T1.JRNENTRY=ins.JRNENTRY
      WHERE T1.SOURCDOC='PATS'

end
Microsoft SQL Server

Avatar of undefined
Last Comment
rwheeler23

8/22/2022 - Mon
OMC2000

You could validate how many records were inserted and inserted values. The first check could be omitted in your case due to inner join in your update statement. The second type of check also seems to be unnecessary in your case because you transparently do it in your update statement, for example:
T1.SOURCDOC='PATS'
rwheeler23

ASKER
Thanks for the tip. It made me remember that I needed to add the SEQNUMBR field to the JOIN. This way only one record will be inserted at a time.

create trigger [dbo].[ORMSTRID] on [dbo].[GL20000] after insert
as
begin


UPDATE dbo.GL20000
      SET ORMSTRID=T2.USERDEF1
      FROM dbo.GL20000 T1
      INNER JOIN dbo.UPR00100 T2 ON T1.ORMSTRID=T2.EMPLOYID
      INNER JOIN inserted ins on T1.JRNENTRY=ins.JRNENTRY and T1.SEQNUMBR=ins.SEQNUMBR
      WHERE T1.SOURCDOC='PATS'

end
ASKER CERTIFIED SOLUTION
OMC2000

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.
rwheeler23

ASKER
OK, so let's say jrnentry = 4321 and there are 4 sequence lines. Each line gets inserted one by one.
Seq line 1 gets inserted and I only want ORMSTRID to be updated on this one line. Isn't this what my insert trigger will do? It will only be doing one line at a time?
Your help has saved me hundreds of hours of internet surfing.
fblack61
OMC2000

If multiple inserts based on statements like
insert into GL20000 (select ....)
are not expected. This extra condition is necessary and correct. Otherwise it won't help.
rwheeler23

ASKER
Thanks