Trigger to update a field in another table

  • I would like to put a trigger in the following scenario, but it doesn't seem to work.

    Table B has foreign key from Table A. Table A has a field that I would like to update from 1 to 0 when a related record is added to Table B or a record in TableB is updated.

    I tried using the inserted table, but it didn't seem to work. I didn't get any errors - the TableA field just didn't get updated.

    I don't quite understand why, it works upon updating a record in TableB, just not an inserting into TableB -

    Text of the trigger is below:

    CREATE TRIGGER trg_UpdateFlag_U ON dbo.TableB

    FOR UPDATE

    AS

    update TableA

    set flag = 0

    from TableA

    inner join TableB

    on TableA.Unique_ID = TableB.Unique_ID

    where TableBPrimaryKey_id in

    (select TableBPrimaryKey_id from inserted)

    Is the inserted table the wrong thing to use for such an operation?

    Thanks

    Edited by - cross on 08/12/2003 1:45:34 PM

  • Because you did not have the insert in the create statement.

    Try this

    CREATE TRIGGER trg_UpdateFlag_U ON dbo.TableB

    FOR INSERT, UPDATE

    AS

    update TableA

    set flag = 0

    from TableA

    inner join TableB

    on TableA.Unique_ID = TableB.Unique_ID

    where TableBPrimaryKey_id in

    (select TableBPrimaryKey_id from inserted)

  • Got it - should have known it was something simple like that. Thanks!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply