【 tulaoshi.com - SQLServer 】
/*备份数据库的过程*/
if exists(
select * from sysobjects
where name=’pr_backup_db’ and xtype=’p’
)
begin
drop proc pr_backup_db
end
go
create proc pr_backup_db
@flag varchar(20) out,
@backup_db_name varchar(128),
@filename varchar(1000) --路径+文件名字
as
declare @sql nvarchar(4000),@par nvarchar(1000)
if not exists(
select * from master..sysdatabases
where name=@backup_db_name
)
begin
select @flag=’db not exist’ /*数据库不存在*/
return
end
else
begin
if right(@filename,1)<’’ and charindex(’’,@filename)<0
begin
select @par=’@filename varchar(1000)’
select @sql=’BACKUP DATABASE ’+@backup_db_name+’ to disk=@filename with init’
execute sp_executesql @sql,@par,@filename
select @flag=’ok’
return
end
else
begin
select @flag=’file type error’ /*参数@filename输入格式错误*/
return
end
end
GO
说明:pr_backup_db过程是备份你的数据库
/*创建函数,得到文件得路径*/
if exists(
select * from sysobjects
where name=’fn_GetFilePath’ and xtype=’fn’
)
begin
drop function fn_GetFilePath
end
go
create function fn_GetFilePath(@filename nvarchar(260))
returns nvarchar(260)
as
begin
declare @file_path nvarchar(260)
declare @filename_reverse nvarchar(260)
select @filename_reverse=reverse(@filename)
select @file_path=substring(@filename,1,len(@filename)+1-charindex(’’,@filename_reverse))
return @file_path
end
GO
/*恢复数据库的过程*/
if exists(
select * from sysobjects
where name=’pr_restore_db’ and xtype=’p’
)
begin
drop proc pr_restore_db
end
go
CREATE proc pr_restore_db
@flag varchar(20) out, /*过程运行的状态标志,是输入参数*/
@restore_db_name nvarchar(128), /*要恢复的数据名字*/
@filename nvarchar(260) /*备份文件存放的路径+备份文件名字*/
as
declare @proc_result tinyint /*返回系统存储过程xp_cmdshell运行结果*/
declare @loop_time smallint /*循环次数*/
declare @max_ids smallint /*@tem表的ids列最大数*/
declare @file_bak_path nvarchar(260) /*原数据库存放路径*/
declare @flag_file bit /*文件存放标志*/
declare @master_path nvarchar(260) /*数据库master文件路径*/
declare @sql nvarchar(4000),@par nvarchar(1000)
declare @sql_sub nvarchar(4000)
declare @sql_cmd nvarchar(100)
declare @sql_kill nvarchar(100)
/*
判断参数@filename文件格式合法性,以防止用户输入类似d: 或者 c:a 等非法文件名
参数@filename里面必须有’’并且不以’’结尾
*/
if right(@filename,1)<’’ and charindex(’’,@filename)<0
begin
select @sql_cmd=’dir ’+@filename
EXEC