SQL SERVER 2005数据库自动备份及清除指定天数前的备份文件
2009-12-02 09:46
打开SQL SERVER 2005代理-->作业--右键新建作业,将以下代码放到作业步骤中的命令里:
declare   @data_3ago   nvarchar(50)  
declare   @cmd   varchar(50)  
   
set   @data_3ago   ='d:\TangGang_JZLIntDB('+convert(varchar(10),getdate()-3,112) +')'    
set   @cmd   =   'del   '+   @data_3ago    
exec   master..xp_cmdshell   @cmd    
go  
   
declare   @data   nvarchar(50)    
set   @data='d:\TangGang_JZLIntDB('+convert(varchar(10),getdate(),112)+')'    
BACKUP   DATABASE   TangGang_GDHIntDB   TO   DISK   =   @data   
    with   init
说明:1、    TangGang_GDHIntDB需要备份的数据库名称,备份后的数据文件名称格式为:    TangGang_JZLIntDB(20090420)   、 TangGang_JZLIntDB(20090421) 等等
           2、     getdate()-3为清除3天前备份的文件,也可按照实际需要修改。
           3、     首次运行上述代码时,提示以下错误:
消息 15281,级别 16,状态 1,过程 xp_cmdshell,第 1 行
SQL Server 阻止了对组件 'xp_cmdshell' 的 过程'sys.xp_cmdshell' 的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用 'xp_cmdshell'。有关启用 'xp_cmdshell' 的详细信息,请参阅 SQL Server 联机丛书中的 "外围应用配置器"。
SQL Server 2005 中引入的 xp_cmdshell 选项是服务器配置选项,使系统管理员能够控制是否可以在系统上执行 xp_cmdshell 扩展存储过程。默认情况下,xp_cmdshell 选项在新安装的软件上处于禁用状态,但是可以通过使用外围应用配置器工具或运行 sp_configure 系统存储过程来启用它,如下示例所示:
1、打开外围应用配置器:勾选启用xp_cmdshell
SQL SERVER 2005数据库自动备份及清除指定天数前的备份文件_职场
2、运行 sp_configure 系统存储过程来启用,代码如下
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO