Link to home
Start Free TrialLog in
Avatar of bongobilly
bongobillyFlag for United States of America

asked on

SQL trigger update insert records

Here is my code for SQL trigger


ALTER TRIGGER [dbo].[AfterUPDATETrigger] on [dbo].[Datatable]
FOR UPDATE
AS DECLARE @cola int,@Colb nvarchar(10)

SELECT @cola = ins.cola from inserted ins
SELECT @Colb = ins.colb from inserted ins

IF @colb ='d'
      BEGIN
            INSERT INTO Datatableb(colz,colx)
            VALUES(@colb,@cola)
      END

This is the data in Datatable
Cola  colb      colc
1      a               30
2      a               30
3      a               30

If I update colb = d where colc = 30
I only insert 1 row into datatableB
I want to get all 3 updates to be entered into datatableb
Avatar of ste5an
ste5an
Flag of Germany image

The basic problem is: Triggers are called per statement. Thus the virtual tables.
 
Currently you only work with arbitrary values.

This should do it:

ALTER TRIGGER [dbo].[AfterUPDATETrigger] ON [dbo].[Datatable]
FOR UPDATE
AS

SET NOCOUNT ON;

INSERT INTO Datatableb(colz,colx)
SELECT  I.ColB, I.ColA
FROM    INSERTED I
WHERE   I.ColB = 'd';

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.