Results 1 to 2 of 2

Thread: Triggers in SQL

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2008
    Posts
    474

    Triggers in SQL

    I have created an AFTERINSERT trigger & INSTEADOFINSERT trigger on tables.
    Code:
    create trigger trig_AFTERINSERT
    on original
    FOR INSERT AS
    BEGIN
    INSERT trigger_original(Roll,UserName,Password)
    SELECT ROLL,Name,Name+'124'
    FROM INSERTED
    END
    Code:
    insert into original values(1,'A')
    WHen I execute the above statemnet, 2 Rows get inserted. ONE ROW IS INSERTED in TABLE - original, ANOTHER ROW GET INSERTED IN TABLE - trigger_original.

    NOW I HAVE CREATED an INSTEADOFINSERT Trigger on the same tables.
    Code:
    create trigger trig_INSTEADOFINSERT
    on original
    INSTEAD OF INSERT
    AS
    INSERT trigger_original(Roll,UserName,Password)
    SELECT ROLL,Name,Name+'124'
    FROM INSERTED
    Code:
    insert into original values(2,'B')
    WHen the above insert statement is executed, I get message 2 Rows Affected.
    But when i select the records

    Code:
    Select * from original
    - IT CONTAINS ONLY THE ONE ROW ( WITH ROLL NO 1)
    Code:
    Select * from trigger_original
    ( TWO ROWS ARE THERE - CORRECT)

    WHy the row is not inserted into table original that is inserted using the INSTEADOF_INSERT Trigger.

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Triggers in SQL

    because you told it to insert into the trigger_original table... not original...

    Code:
    INSERT trigger_original(Roll,UserName,Password)
    SELECT ROLL,Name,Name+'124'
    FROM INSERTED
    It did exactly what you told it to do...

    That said... it is DANGEROUS to insert into the same table you're triggering off of... you could end up in an endless loop that could cause the system to crash...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width