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

來源:互聯網
上載者:User

--方法2. 指令碼複製
use master
go

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.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''  --資料庫首碼
as
declare @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
end

if 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_output
go

上一篇: 根據當月資料庫自動產生下個月資料庫--1

下一篇: 根據當月資料庫自動產生下個月資料庫--3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.