SQL SERVER 2019 自动还原数据库bak文件

SQL SERVER 2019 自动还原数据库bak文件_第1张图片

SQL SERVER 2019 自动还原数据库bak文件_第2张图片

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestoreBak
{
    class Program
    {
        static void Main(string[] args)
        {
            var RestorePath = "c:\\database\\";
            var bakupFilePath = "c:\\db\\";
            Console.WriteLine("用法:RestoreBak \"备份bak文件路径\"  \"还原路径\"");
            Console.WriteLine("默认:RestoreBak \"{0}\"  \"{1}\"",bakupFilePath,RestorePath);
            Console.WriteLine("正在创建还原脚本...!");
            
            if (args.Length == 2)
            {
                bakupFilePath = args[0];
                RestorePath = args[1];
            }
            var restoreSql = "";
            var tmpFile = "c:\\RESTORE_SQL.SQL";
            foreach (var bakfile in System.IO.Directory.GetFiles(bakupFilePath, "*.bak"))
            {
                var DatabaseName = System.IO.Path.GetFileName(bakfile).Split('.')[0];
                restoreSql += string.Format(@"
                                    RESTORE DATABASE {0}
                                    FROM DISK = '{1}'
                                    WITH MOVE '{0}' TO '{2}{0}.mdf',
                                         MOVE '{0}_log' TO '{2}{0}_log.ldf'
                              ", DatabaseName, bakfile, RestorePath);
            }
            System.IO.File.WriteAllText(tmpFile, restoreSql);
            System.Diagnostics.Process p = System.Diagnostics.Process.Start("osql.exe",string.Format(" -E -i {0} ",tmpFile));
            while (!p.HasExited) 
            {
                Console.Write(">");
            }
            Console.WriteLine("\n数据库还原成功!");
            Console.ReadKey();
        }
    }
}

 

你可能感兴趣的:(Windows,sql,sqlserver,数据库,.net)