根據當月資料庫自動生成下個月資料庫 2

2021-03-31 15:29:46 字數 2651 閱讀 5847

--方法2. 指令碼複製

use master

goif 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.exe

scptxfr.rll

將其複製到下述目錄

%systemroot%/system32/

--鄒建 2005.03(引用請保留此資訊)--*/

/*--呼叫示例

-- 複製 pos

exec sp_proccopydb 'pos'

--*/

--1.master 資料庫中建立乙個處理的儲存過程,實現當月資料庫到下月資料的自動複製

/*--系統需求

需要如下兩個檔案,可以在sql安裝盤 x86/upgrade 目錄下找到

scptxfr.exe

scptxfr.rll

將其複製到下述目錄

%systemroot%/system32/

--*/

create proc sp_proccopydb

@db_head sysname=n''  --資料庫字首

asdeclare @sdbname sysname,@ddbname sysname

declare @s nvarchar(4000),@bkfile nvarchar(1000)

--複製的源庫名及目標庫名

select @sdbname=@db_head+convert(char(6),getdate(),112),

@ddbname=@db_head+convert(char(6),dateadd(month,1,getdate()),112)

if db_id(@sdbname) is null

begin

raiserror(n'源資料庫"%s"不存在',1,16,@sdbname)

return

endif db_id(@ddbname) is not null

begin

raiserror(n'目標資料庫"%s"已經存在',1,16,@ddbname)

return

end--臨時備份檔案名

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 "'+@bkfile+'"'

exec master..xp_cmdshell @s,no_outputgo

根據當月資料庫自動生成下個月資料庫 2

方法2.指令碼複製 use master goif exists select from dbo.sysobjects where id object id n dbo sp proccopydb and objectproperty id,n isprocedure 1 drop procedur...

根據當月資料庫自動生成下個月資料庫 2

方法2.指令碼複製 use master goif exists select from dbo.sysobjects where id object id n dbo sp proccopydb and objectproperty id,n isprocedure 1 drop procedur...

根據當月資料庫自動生成下個月資料庫 3

建立乙個每月最後乙個工作日執行的作業,呼叫上述儲存過程實現自動建立資料庫 use master go 設定 sql agent 服務為自動啟動 exec msdb.sp set sqlagent properties auto start 1 go 建立作業 exec msdb.sp add job...