Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert trigger copy row to another duplicate table SQL Server 2008

Overview: Trying to write a trigger for a SQL Server 2008 database. TableA and TableB have the same schema.

Aim: On an insert into TableA, copy everything in that row to a new row in TableB

Notes so far:

Using this question I manage to get most the way, but then stumbled into a problem with

Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables.

I just have text columns, but I want to copy them too.

I found this website which seems to have a workaround but, it is working on update, and I haven't been able to apply it to my insert example...

Any ideas?

Edit: purpose is to add functionality to an existing product, I can't change schema of TableA unfortunately.

like image 995
baron Avatar asked Mar 20 '12 23:03

baron


People also ask

How copy data from one table to another using trigger?

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 I copy a row from one table to another in SQL?

Using SQL Server Management StudioOpen the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design. Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy.

Can two tables have same triggers?

You can create multiple triggers for the same subject table, event, and activation time. The order in which those triggers are activated is the order in which the triggers were created.

What is instead of insert trigger?

An INSTEAD OF trigger is an SQL trigger that is processed “instead of” an SQL UPDATE, DELETE or INSERT statement. Unlike SQL BEFORE and AFTER triggers, an INSTEAD OF trigger can be defined only on a view, not a table.


1 Answers

I'm not sure why you can't use the example you linked to. It should be as simple as:

CREATE TRIGGER T_TableA_I
on TableA
after insert
as
    set nocount on

    insert into TableB (ColumnA,ColumnB,/* Columns in table b */)
    select a.ColumnA,a.ColumnB, /* Columns from table a */
    from
        TableA a
            inner join
        inserted i
            on
                a.PKColumn1 = i.PKColumn1 and
                a.PKColumn2 = i.PKColumn2 /* Primary Key columns from table A */

Of course, your question doesn't contain any table definitions, so the above will need quite a bit of modification. Hopefully, you can work out what to add/remove from the above, where comments exist.

like image 159
Damien_The_Unbeliever Avatar answered Sep 21 '22 20:09

Damien_The_Unbeliever