SQL Server 2000DBAWindows 2003.NET 1.1Windows 2000Windows XPHTML中级开发Visual StudioSQL ServerSQLWindows.NETC#
将 SQL Server 备份文件还原到任何数据库






4.80/5 (29投票s)
2005年10月24日

168468

4921
创建备份时,您必须能够将此备份还原到相同的数据库和相同的位置。但这段代码还可以帮助您将备份还原到新的数据库或现有数据库。
引言
从 Microsoft SQL Server 数据库创建备份时,默认情况下必须将备份还原到相同的数据库和相同的位置。但如果您想将此备份还原到另一台服务器上的另一个位置,则必须使用自定义的 T-SQL 脚本。此操作会消耗大量时间。
自定义 T-SQL 备份语句
现在您可以使用自定义的 T-SQL 语句将数据库还原到任何位置。例如
RESTORE DATABASE NewNorthwind
FROM DISK = 'C:\Northwind.BAK'
WITH
MOVE 'Northwind_Data' TO 'C:\NewNorthwind_Data.mdf' ,
MOVE 'Northwind_Log' TO 'C:\NewNorthwind_log.ldf', REPLACE
此脚本必须为每个数据库生成。
从程序集加载 T-SQL 语句
我们可以通过将新文件添加到项目并将 **构建操作** 属性设置为 **嵌入式资源**,在 Exe 或 DLL 文件中存储 T-SQL 语句。例如,将名为 *Restore.sql* 的新文件添加到项目并设置构建操作属性。现在要从程序集加载它,请使用该函数
private string LoadSQLFromAssembly (string Name)
{
System.IO.Stream stream =
this.GetType().Assembly.GetManifestResourceStream(this.GetType(),
"SQL." + Name);
if(stream == null)
{
MessageBox.Show("Internal Error occured! Close Application" +
" & try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
System.IO.StreamReader reader= new System.IO.StreamReader(stream);
if (reader == null)
{
MessageBox.Show("Internal Error occured! Close Application" +
" & try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string s = reader.ReadToEnd();
reader.Close();
return s;
}