- --目前只适合SQL2005,SQL2000的不行
- --批量附加数据库备份例子:
- --exec attach_db_pro 'c:\program files\microsoft sql server\data'
- if object_id('attach_db_pro') is not null
- drop procedure attach_db_pro
- go
- create procedure attach_db_pro
- @dir nvarchar(520)
- as
- declare @dbname varchar(20)
- declare @filename nvarchar(520)
- declare @name sysname
- declare @temp_db_name varchar(20)
- declare @i int
- declare my_cursor cursor
- for
- select db_name(dbid) dbname,name,filename from master..sysaltfiles
- open my_cursor
- fetch next from my_cursor into @dbname,@name,@filename
- while @@fetch_status = 0
- begin
- set @temp_db_name = @dbname
- set @i = 1
- print 'exec sp_attach_db @db_name = ' + @dbname + ',@filename' + convert(varchar,@i) + ' = ''' + @dir + '\' + @name + right(@filename,4)+''''
- fetch next from my_cursor into @dbname,@name,@filename
- while @@fetch_status = 0 and @temp_db_name = @dbname
- begin
- set @i = @i + 1
- print ',@filename' + convert(varchar,@i) + ' = ''' + @dir + '\'+@name+right(@filename,4)+''''
- fetch next from my_cursor into @dbname,@name,@filename
- end
- print ''
- end
- close my_cursor
- deallocate my_cursor
- go
或者使用以下的办法来生成附加数据库的角本.
private static void att_database()
{
string tmp = "";
FileInfo info = null;
string[] s = Directory.GetFiles(@"D:\03backup\JujuyaDataBase\WebsiteDatabase","*.mdf");
foreach (string str in s)
{
info = new FileInfo(str);
Logs.Log.WriteLog("EXEC sp_attach_db @dbname = N'" + info.Name.Replace(".mdf","") + "'"+
" ,@filename1 = N\'D:\\03backup\\JujuyaDataBase\\WebsiteDatabase\\" + info.Name +"'"+
" ,@filename2 = N\'D:\\03backup\\JujuyaDataBase\\WebsiteDatabase\\" + info.Name.Replace(".mdf", "_log.LDF") + "'"
);
}
}