I'm trying to implement the following logic in SQL Server:
every time data is inserted into MainTable
, all this data should be also inserted into a backup table MainTable_BACKUP
, and every row inserted into MainTable
should have a foreign key BackupRecordId
pointing to MainTable_BACKUP
.
Can it be achieved using a trigger?
CREATE TRIGGER TRG_MainTable
ON MainTable
AFTER INSERT AS
BEGIN
INSERT INTO MainTable_BACKUP
SELECT *
FROM INSERTED
-- UPDATE INSERTED SET BackupRecordId = ??? somehow...
END
Yes you can.
Assuming that you have an identity column named BackupRecordId on you MainTable_BACKUP table, you can create an after insert trigger like this
Create Table MainTable
(
ID int IDENTITY(1, 1) PRIMARY KEY,
Description NVARCHAR(50),
BackupRecordId int
)
Create table MainTable_BACKUP
(
BackupRecordId int IDENTITY(1, 1) PRIMARY KEY,
[Id] int,
Description NVARCHAR(50)
)
CREATE TRIGGER TRG_MainTable
ON MainTable
AFTER INSERT AS
BEGIN
INSERT INTO MainTable_BACKUP([Id], Description)
SELECT [Id], Description FROM INSERTED
UPDATE MainTable
SET BackupRecordId = MP.BackupRecordId
FROM MainTable
INNER JOIN inserted i on i.Id = MainTable.Id
INNER JOIN MainTable_BACKUP MP ON MP.Id = MainTable.Id
END
You can try it with this:
insert into MainTable(Description)
values ('Testing')
select * from MainTable
select * from MainTable_BACKUP
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.