You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在SQL Server作业的数据库备份文件名中添加YYYYMMDD格式日期?

Adding YYYYMMDD Date Stamp to SQL Backup Filenames in SQL Agent Jobs

Got it, adding that YYYYMMDD date stamp to your backup filenames is a common and straightforward need—here are two reliable methods to pull this off, depending on how you're running your backups:

Method 1: Dynamic T-SQL Script (Best for Custom Jobs)

This is the most flexible approach if you're writing your own backup script for a SQL Agent Job. You'll use T-SQL variables to build the filename with the exact date format you want.

First, define your base backup path and construct the filename using GETDATE() with style 112 (this style outputs the date in pure YYYYMMDD format, no slashes or hyphens):

-- Set your base backup directory (adjust this to your actual path)
DECLARE @BackupPath NVARCHAR(500) = N'C:\SQL_Backups\';
-- Build the filename: DatabaseName_YYYYMMDD.bak
DECLARE @BackupFileName NVARCHAR(1000) = 
    @BackupPath + N'YourDatabaseName_' + 
    CONVERT(NVARCHAR(8), GETDATE(), 112) + 
    N'.bak';

-- Run the backup with the dynamic filename
BACKUP DATABASE YourDatabaseName
TO DISK = @BackupFileName
WITH COMPRESSION, INIT, STATS = 10;
  • Replace YourDatabaseName and @BackupPath with your actual database name and backup directory.
  • The CONVERT(NVARCHAR(8), GETDATE(), 112) snippet is the key here—it’s the standard way to get YYYYMMDD in T-SQL without extra formatting hoops.

Method 2: SQL Server Maintenance Plan (For GUI-Based Setups)

If you prefer using Maintenance Plans to handle backups, you can enable the date stamp directly in the backup task:

  • Open your Maintenance Plan and edit the Backup Database Task.
  • Go to the Destination tab.
  • Under "Backup to disk", click Add—instead of a static filename, use template variables like: C:\SQL_Backups\<DatabaseName>_<Date>.bak
  • Click the Options button next to the filename field.
  • In the "File name options" section, select Use the following format and pick yyyyMMdd from the dropdown (or manually enter 112 in the "Format" box for exact YYYYMMDD).
  • Save the plan, and your next backup will automatically include the correct date stamp in the filename.

Quick Tips to Avoid Issues

  • Make sure the SQL Agent service account has read/write permissions on the backup directory—this is a common reason backups fail silently.
  • For network shares, use UNC paths (like \\ServerName\BackupShare\) instead of mapped drives, since mapped drives might not be accessible to the SQL Agent service.

内容的提问来源于stack exchange,提问作者Waqar Baryar

火山引擎 最新活动