Wednesday, December 18, 2024

SQL BACKUP DATABASE for SQL Server

 To back up a database in SQL Server, you can use the BACKUP DATABASE command. Below is an example of how to back up a database:

Syntax:

BACKUP DATABASE [YourDatabaseName]
TO DISK = 'C:\Path\To\Backup\YourDatabaseName.bak'
WITH FORMAT, INIT;

Parameters:

  • YourDatabaseName: The name of the database you want to back up.
  • DISK: Specifies the path and file name for the backup.
  • WITH FORMAT: Creates a new backup file, overwriting the existing one.
  • WITH INIT: Initializes the backup, overwriting any existing backup files on the specified disk.

Example:

BACKUP DATABASE AdventureWorks
TO DISK = 'C:\Backups\AdventureWorks_Backup.bak'
WITH FORMAT, INIT;

Additional Options:

You can also add options for compression, encryption, or to back up specific parts (e.g., filegroups). Here's an example that includes compression:

BACKUP DATABASE AdventureWorks
TO DISK = 'C:\Backups\AdventureWorks_Backup.bak'
WITH COMPRESSION, FORMAT, INIT;

To create a differential backup (only the changes since the last full backup):

BACKUP DATABASE AdventureWorks
TO DISK = 'C:\Backups\AdventureWorks_Diff.bak'
WITH DIFFERENTIAL;

Restoring the Backup:

To restore the database, use the RESTORE DATABASE command:

RESTORE DATABASE AdventureWorks
FROM DISK = 'C:\Backups\AdventureWorks_Backup.bak';

This command will restore the database to the state it was in at the time of the backup.

No comments:

Post a Comment