Restore a database using a Job in SQL Server 2005

  • Hi guys, I have a question, how can I restore a database using a Job in a specific schedule, I'm working with SQL Server 2005...

    Thanks...

  • Create a sql agent job with a restore script like the one below; if you need to restore over an existing db then firstly would be to set the db (UserDBCopy below) in single user mode, then add "WITH REPLACE" to the restore line in script, then bring your restored db in multi-user mode.

    Declare

    @vDataFileName

    Varchar(255),

    @vFileName

    Varchar(100),

    @vDataPath

    Varchar(100),

    @vLogPath

    Varchar(100),

    @vRestoreString

    Varchar(1000)

    Set

    @vDBName='UserDB'

    Set

    @vFileName='YourBackupPath\BackupFileName.bak'

    Set

    @vDataFileName='UserDB_Data'

    Set

    @vDataPath='YourDataPath\UserDBCopy_Data'

    Set

    @vLogFileName='UserDB_Log'

    Set

    @vLogPath='YourLogPath\UserDBCopy_Log'

    Set

    @vRestoreString = 'RESTORE DATABASE [UserDBCopy] FROM

    DISK '''

    + @vFileName

    + ''' WITH FILE = 1, MOVE N''' +

    @vDataFileName

    + '''TO N'''+ @vDataPath + ', MOVE N'''+ @vLogFileName + '''TO N'''

    + @vLogPath +', NOUNLOAD,

    STATS = 10'

    Exec

    (@vRestoreString)

    GO

    Good luck.

  • You don't need to set user databases in single user mode.  To have a succesfull restore you do need to make sure none is connected to the database though.

     

  • ..so you can use some kind of kill users stored procedures in the previous step...

  • you can do the same using alter database command...

    ALTER DATABASE <DBNAME> set single_user rollback immediate...

    check BOL for correct syntax...

     

    MohammedU
    Microsoft SQL Server MVP

  • I like to do it this way, because it prevents anyone from connecting to the database.  Even a single user connection will cause the restore to fail.

    use master
    alter database My_Database_Name set offline with rollback immediate
    

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply