Link to home
Start Free TrialLog in
Avatar of rwheeler23
rwheeler23Flag 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
Avatar of OMC2000
OMC2000
Flag of Russian Federation image

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'
Avatar of 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
Avatar of OMC2000
OMC2000
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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?
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.
Thanks