Inserting New Row Values into Another Table Using SQL Server Trigger
Consider the following scenario: you want to monitor insertions in the aspnet_users table and record the new user's ID and name in a separate table. To achieve this, you intend to create a trigger on aspnet_users that captures these values. However, you seek a more efficient method than selecting by the latest date_created.
The solution lies in leveraging the INSERTED virtual table, which provides access to the values inserted during the triggering event. Here's a concise SQL Server trigger that inserts new user_id and user_name into another table:
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
This trigger efficiently captures the new row's data and inserts it into yourDestinationTable. The INSERTED table allows you to access the inserted values directly, ensuring accuracy and performance.
The above is the detailed content of How Can I Efficiently Insert New Row Values from One SQL Server Table into Another Using a Trigger?. For more information, please follow other related articles on the PHP Chinese website!