Sql-server – Know when a database has been restored

restoresql serversql-server-2008

I'm using SQL Server 2008. I would like to know if a specific database has been restored from a device and when did it happened. Is it possible?

Best Answer

In the msdb database, there is a table named restorehistory:

declare @DB sysname = 'MyDB';
select * from msdb.dbo.restorehistory where destination_database_name = @DB;

This is a table that people with sufficient privileges can clear out, but if the restore was recent and you don't have a job which clears out this table (or if it hasn't run between then and now), you should be able to see the login which performed the restore.

EDIT

You can also join it to a couple of other tables (if they have relevant data): backupset and backupmediafamily. If there are records there--with the same retention caveats as before--they'll tell you more about the backup file(s) used to restore:

declare @DB sysname = 'MyDB';
select
    rh.destination_database_name,
    rh.user_name,
    bs.name as backup_set_name,
    bs.user_name as backup_set_username,
    bs.backup_start_date,
    bs.backup_finish_date,
    bs.database_name as backup_set_database_name,
    bs.server_name,
    bs.machine_name,
    bmf.physical_device_name,
    bmf.device_type,
    case bmf.device_type
        when 2 then 'Disk'
        when 5 then 'Tape'
        when 7 then 'Virtual Device'
        when 105 then 'Permanent backup device'
        else 'UNKNOWN'
    end as device_type_desc
from 
    msdb.dbo.restorehistory rh
    left outer join msdb.dbo.backupset bs on rh.backup_set_id = bs.backup_set_id
    left outer join msdb.dbo.backupmediafamily bmf on bs.media_set_id = bmf.media_set_id
where
    rh.destination_database_name = @DB;

That way, you could also filter on device type or file location.