Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server command line backup statement

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?

like image 796
Alex Avatar asked May 19 '09 00:05

Alex


People also ask

What is backup command in SQL?

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).

What is database backup command?

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.

How do I backup a SQL Server database using a script?

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).


1 Answers

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 
like image 80
Seba Illingworth Avatar answered Sep 19 '22 09:09

Seba Illingworth