【Vegas原创】用proc来做SQL数据库备份与还原
一、DB备份:FlowER DB为例:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/***********************************
删除一周前资料;备份当天资料
For FLowER、持续改善系统
Vegas Add 08-09-29
************************************/
ALTER proc [dbo].[FlowER_backup]
as
declare @data_7ago nvarchar(50) --获取七天前日期
declare @cmd varchar(50) --cmd 指令
--删除七天前的备份资料
set @data_7ago ='\\10.91.50.107\DBBackup\FlowER\'+convert(varchar(10),getdate()-7,112)
set @cmd = 'del '+ @data_7ago
exec master..xp_cmdshell @cmd
go
-- 备份当天资料
declare @data nvarchar(50)
set @data='\\10.91.50.107\DBBackup\FlowER\'+convert(varchar(10),getdate(),112)
BACKUP DATABASE FlowER TO DISK = @data
with init
set QUOTED_IDENTIFIER ON
go
/***********************************
删除一周前资料;备份当天资料
For FLowER、持续改善系统
Vegas Add 08-09-29
************************************/
ALTER proc [dbo].[FlowER_backup]
as
declare @data_7ago nvarchar(50) --获取七天前日期
declare @cmd varchar(50) --cmd 指令
--删除七天前的备份资料
set @data_7ago ='\\10.91.50.107\DBBackup\FlowER\'+convert(varchar(10),getdate()-7,112)
set @cmd = 'del '+ @data_7ago
exec master..xp_cmdshell @cmd
go
-- 备份当天资料
declare @data nvarchar(50)
set @data='\\10.91.50.107\DBBackup\FlowER\'+convert(varchar(10),getdate(),112)
BACKUP DATABASE FlowER TO DISK = @data
with init
二、DB还原:
1,要Kill掉数据库进程的proc:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/*
断开所有用户打开的连接
Vegas Add 08.09.29
*/
ALTER proc [dbo].[p_killspid]
@dbname sysname --要关闭进程的数据库名
as
declare @s nvarchar(1000)
declare tb cursor local for
select s='kill '+cast(spid as varchar)
from master..sysprocesses
where dbid=db_id(@dbname)
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb
set QUOTED_IDENTIFIER ON
go
/*
断开所有用户打开的连接
Vegas Add 08.09.29
*/
ALTER proc [dbo].[p_killspid]
@dbname sysname --要关闭进程的数据库名
as
declare @s nvarchar(1000)
declare tb cursor local for
select s='kill '+cast(spid as varchar)
from master..sysprocesses
where dbid=db_id(@dbname)
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb
2,进行还原:DBBackup DB为例
exec dbo.p_killspid 'DBBackup'
RESTORE DATABASE DBBackup
FROM DISK = '\\10.91.50.107\DBBackup\DBBackup\20080929'
WITH REPLACE
RESTORE DATABASE DBBackup
FROM DISK = '\\10.91.50.107\DBBackup\DBBackup\20080929'
WITH REPLACE
或将备份文件加.bak后缀名,从SQL Server还原。
PS:用SQL Server进行还原的注意事项:
1)新建一个test数据库,点击还原,在选项里选择“覆盖现有数据库”
2) 如报数据库 '***' 正在使用该文件,在选项里更新新的数据文件 。
喜欢请赞赏一下啦^_^