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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With