--方法2. 脚本复制use mastergo
if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[sp_proccopydb]') and objectproperty(id, n'isprocedure') = 1)drop procedure [dbo].[sp_proccopydb]go
/*--数据库自动复制
将指定前缘的数据库,复制为一个以当前月份+1为库名的数据库中,并且清除所有的数据例如,数据库前缘为 pos ,当前日期为 2005-3-27则要求复制数据 pos200503 为 pos200504,并且清空里面的数据
用生成源库脚本的方法实现好处是速度快,不需要考虑源数据库的数据但如果要保留源数据库的部分数据,则要专门做数据复制处理
--运行需求需要如下两个文件,可以在sql安装盘 x86/upgrade 目录下找到scptxfr.exescptxfr.rll
将其复制到下述目录%systemroot% ystem32/--邹建 2005.03(引用请保留此信息)--*/
/*--调用示例
-- 复制 posexec sp_proccopydb 'pos'--*/
--1.master 数据库中创建一个处理的存储过程,实现当月数据库到下月数据的自动复制
/*--系统需求需要如下两个文件,可以在sql安装盘 x86/upgrade 目录下找到scptxfr.exescptxfr.rll
将其复制到下述目录%systemroot% ystem32/--*/
create proc [email protected]_head sysname=n'' --数据库前缀asdeclare @sdbname sysname,@ddbname sysnamedeclare @s nvarchar(4000),@bkfile nvarchar(1000)
--复制的源库名及目标库名select @[email protected]_head+convert(char(6),getdate(),112),@[email protected]_head+convert(char(6),dateadd(month,1,getdate()),112)
if db_id(@sdbname) is nullbeginraiserror(n'源数据库"%s"不存在',1,16,@sdbname)returnend
if db_id(@ddbname) is not nullbeginraiserror(n'目标数据库"%s"已经存在',1,16,@ddbname)returnend
--临时备份文件名select top 1 @bkfile=rtrim(reverse(filename)) from master.dbo.sysfiles where name=n'master'select @bkfile=stuff(@bkfile,1,charindex('/',@bkfile),n''),@bkfile=reverse(stuff(@bkfile,1,charindex('/',@bkfile),n''))+n'/backup/'+cast(newid() as nvarchar(36))+n'.sql'
--脚本生成处理set @s=n'scptxfr /s '+quotename(cast(serverproperty(n'servername') as nvarchar),n'"')+n' /d '+quotename(@sdbname,n'"')+n' /i' --使用windows身份验证,如果使用sql身份验证,则愀为 +n' /p "sa密码"',固定使用sa用户+n' /f '+quotename(@bkfile,n'"')+n' /y /q /t /c /y'exec master..xp_cmdshell @s,no_output
--创建目标数据库set @s=n'create database '+quotename(@ddbname)exec sp_executesql @s
--使用源库脚本,为目标数据库创建对象set @s=n'osql /s'+quotename(cast(serverproperty(n'servername') as nvarchar),n'"')+n' /d '+quotename(@ddbname,n'"')+n' /e' --使用windows身份验证,如果使用sql身份验证,则愀为 +n' /u"sa" /p"sa密码"'+n' /i'+quotename(@bkfile,n'"')exec master..xp_cmdshell @s,no_output
--删除临时备份文件set @s='del "'[email protected]+'"'exec master..xp_cmdshell @s,no_outputgo