Does any one know if there is a way to script out SQL Server backup in to a batch file, so that it could be executed from a command line?
Backs up a complete SQL Server database to create a database backup, or one or more files or filegroups of the database to create a file backup (BACKUP DATABASE). Also, under the full recovery model or bulk-logged recovery model, backs up the transaction log of the database to create a log backup (BACKUP LOG).
The command is BACKUP DATABASE databaseName. The "TO DISK" option specifies that the backup should be written to disk and the location and filename to create the backup is specified.
Right-click the database that you wish to backup, point to Tasks, and then select Back Up.... In the Back Up Database dialog box, the database that you selected appears in the drop-down list (which you can change to any other database on the server).
Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:
BACKUP:
echo off cls echo -- BACKUP DATABASE -- set /p DATABASENAME=Enter database name: :: filename format Name-Date (eg MyDatabase-2009.5.19.bak) set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2% set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak set SERVERNAME=your server name here echo. sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT" echo. pause
RESTORE:
echo off cls echo -- RESTORE DATABASE -- set /p BACKUPFILENAME=Enter backup file name:%CD%\ set /p DATABASENAME=Enter database name: set SERVERNAME=your server name here sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE" :: WARNING - delete the database, suits me :: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]" :: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]" :: restore sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE" :: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx) sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'" sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER" echo. pause
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