Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server trigger insert values from new row into another table

I have a site using the asp.net membership schema. I'd like to set up a trigger on the aspnet_users table that inserted the user_id and the user_name of the new row into another table.

How do I go about getting the values from the last insert?

I can select by the last date_created but that seems smelly. Is there a better way?

like image 445
jim Avatar asked Feb 11 '10 21:02

jim


People also ask

How do you insert values into a table using triggers?

To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. To check if the records are inserted in both tables or not.

How do you create a trigger after insert?

First, specify the name of the trigger that you want to create after the CREATE TRIGGER keywords. Second, use AFTER INSERT clause to specify the time to invoke the trigger. Third, specify the name of the table on which you want to create the trigger after the ON keyword.

What is insert trigger in SQL?

Triggers are database operations which are automatically performed when an action such as Insert, Update or Delete is performed on a Table or a View in database. Triggers are associated with the Table or View directly i.e. each table has its own Triggers.


3 Answers

try this for sql server

CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS

INSERT INTO yourDestinationTable
        (col1, col2    , col3, user_id, user_name)
    SELECT
        'a'  , default , null, user_id, user_name
        FROM inserted

go
like image 86
KM. Avatar answered Oct 11 '22 19:10

KM.


You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.

Delete triggers have access to a similar logical table called DELETED.

Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.

like image 16
Oded Avatar answered Oct 11 '22 19:10

Oded


You can use OLDand NEW in the trigger to access those values which had changed in that trigger. Mysql Ref

like image 5
Teja Kantamneni Avatar answered Oct 11 '22 21:10

Teja Kantamneni