简体   繁体   中英

How to use backup with triggers in SQL Server 2008?

I have a table (Cycle) and I created a trigger

alter trigger AnyName on Cycles
for insert,update,delete
AS
BACKUP DATABASE medrepcrm TO  DISK = N'C:\medrepcrm.bak' WITH NOFORMAT, INIT,  NAME = N'pcrm-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

But when I insert, update, or delete in the Cycle table that leads to an error.

Msg 3021, Level 16, State 0, Procedure AnyName, Line 8
Cannot perform a backup or restore operation within a transaction.
Msg 3013, Level 16, State 1, Procedure AnyName, Line 8
BACKUP DATABASE is terminating abnormally.
The statement has been terminated.

What can I do to fix this error?

BACKUP DATABASE on MSDN says

The BACKUP statement is not allowed in an explicit or implicit transaction.

A trigger is always in a transactions

If you work it through, a backup which is transactionally consistent snapshot of a database: it doesn't make sense for it to be in it's own transaction.

Not least, on RESTORE the roll forward/roll back mechanism would have to rollback the transaction containing the backup... which defeats the purpose of the backup in the first place...

You could start a job sp_start_job . Within the job you execute a stored procedure where you execute the backup statement. I've done this already with a server trigger which is fired when a new database is created.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM