Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. SQL Server
  4. Batch Script for Creating Database backups from Sql server

Batch Script for Creating Database backups from Sql server

Date- Apr 30,2022 Updated Jan 2026 11175
Batch Script Database backup

Overview of Database Backups

Database backups are a crucial part of database management and administration. They serve as a safety net, enabling recovery of data in case of corruption, accidental deletion, or hardware failures. By automating backups, organizations can ensure that their data is consistently protected without manual intervention.

In this tutorial, we will walk through creating a batch script that connects to a SQL Server instance and performs backups of specified databases. This approach is especially beneficial for businesses that require regular backups to maintain compliance with data protection regulations and to safeguard against data loss.

Prerequisites

Before diving into the script, ensure you have the following prerequisites in place:

  • SQL Server: A running instance of SQL Server with databases you wish to back up.
  • Access Rights: SQL Server login credentials with sufficient permissions to perform backups.
  • Windows Environment: A Windows environment to execute the batch file.
  • PowerShell: Basic knowledge of PowerShell and batch scripting.

Creating a Batch File for Database Backups

We can use a .bat file to write a script that automates database backup from the server. Below is a sample batch script that you can customize based on your SQL Server configuration.

@ECHO OFF
CLS
REM SET VARIABLE VALUES
SET SqlServer=Code2night\SQL2017
SET Username=sa
SET Password=Admin123
SET BaseFolderPath=C:\DatabaseScript\DatabaseScriptBackup
SET TodayDate=%DATE:/=%
SET LocalFolder=%BaseFolderPath%\Backups
SET Databases=%LocalFolder%\Databases.txt

IF NOT EXIST %LocalFolder% mkdir %LocalFolder%

REM SAVE DATABASES LIST IN TEMP FILE
SqlCmd -S %SqlServer% -U %Username% -P %Password% -Q "SET NOCOUNT ON; SELECT Name FROM master.dbo.sysDatabases WHERE [Name] IN ('ALISTrucking','ALISTruckingClean','ALISTruckingPreProd')" > "%Databases%"

REM SAVE BACKUP OF EACH DATABASE
FOR /F "tokens=* delims=" %%I IN (%Databases%) DO (
    ECHO Backing up database: %%~nI
    sqlcmd -S %SqlServer% -U %Username% -P %Password% -Q "BACKUP DATABASE %%~nI TO DISK = '%LocalFolder%\%%~nI_%TodayDate%.bak' WITH NOFORMAT, INIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10;"
    ECHO.
)

REM DELETE TEMP DATABASES LIST
IF EXIST "%Databases%" DEL /F /Q "%Databases%"
ECHO DB Backup finished...

In this script, we set several variables such as the SQL Server instance name, username, and password. The script then creates a local folder for backups if it doesn't already exist, retrieves the list of databases we want to back up, and iterates through each database to create a backup file.

Executing the Batch Script

After creating the script, save the file with a .bat extension. To execute the script, simply double-click on the file. The script will run and create backups of the specified databases in the designated folder.

To verify the success of the operation, navigate to the backup folder and check for the presence of the .bak files corresponding to your databases. Regularly check your backups to ensure they are being created as expected.

Edge Cases & Gotchas

When working with batch scripts for database backups, there are several edge cases and potential pitfalls to be aware of:

  • Permissions: Ensure that the SQL Server login used has the necessary permissions to perform backups. Insufficient permissions may lead to failed backup attempts.
  • File Path Length: Windows has a maximum path length limitation. Ensure that your backup paths do not exceed this limit to avoid errors.
  • Disk Space: Monitor the available disk space on the backup location. Running out of space can lead to failed backups.
  • Database State: Ensure that the databases are in a state that allows backups. For example, databases in recovery mode may not be backed up successfully.

Performance & Best Practices

To optimize the performance of your database backups and ensure best practices, consider the following recommendations:

  • Schedule Backups: Automate your backups using Windows Task Scheduler to run the batch script at regular intervals, such as nightly or weekly.
  • Use Compression: Enabling backup compression can significantly reduce the size of backup files, leading to faster backup and restore times.
  • Test Your Backups: Regularly test your backup files by restoring them to a test environment to ensure they are valid and usable.
  • Monitor Backup Jobs: Implement monitoring to alert you of any failures or issues with the backup jobs, allowing for timely resolution.

Conclusion

In this article, we have explored how to create a batch script for automating SQL Server database backups. By following the steps outlined above, you can ensure that your data is regularly backed up and protected against loss.

Key Takeaways:

  • Database backups are essential for data protection and recovery.
  • Batch scripts can automate the backup process, saving time and effort.
  • Monitor and manage your backup processes to ensure reliability.
  • Regularly test your backups to confirm their integrity and usability.
Database Backup Script Example

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Best Practices for Secure Gemini API Integration in ASP.NET
Apr 03, 2026
How to Import CSV in ASP.NET MVC
Feb 02, 2024
How to refund payment using Paypal in Asp.Net MVC
Jan 30, 2024
How to Use Stored Procedures with Parameters in Dapper
Jan 23, 2024
Next in SQL Server
How to read json in Sql Server
Buy me a pizza

Comments

On this page

๐ŸŽฏ

Interview Prep

Ace your SQL Server interview with curated Q&As for all levels.

View SQL Server Interview Q&As

More in SQL Server

  • How to create a read-only MySQL user 10251 views
  • How to Connect to a Database with MySQL Workbench 7583 views
  • How to find all procedures having table reference in Sql ser… 6940 views
  • How to find all tables by column name 6524 views
  • Converting commas or other delimiters to a Table or List in … 6456 views
View all SQL Server posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor