我的C#应用程序使用SMO对用户选择的sql Server实例进行各种操作.特别是,它改变了认证模式:
ServerConnection conn = new ServerConnection(connection); Server server = new Server(conn); server.Settings.LoginMode = ServerLoginMode.Mixed;
更改登录后,应重新启动更多实例.但是,我在SMO中找不到任何方式来重启所选实例.
我试图谷歌这个,但只发现了一堆枚举正在运行的服务并将其名称与sql服务器服务名称进行比较的示例.我不喜欢这种方式,因为它容易出错并且依赖于Microsoft当前命名sql服务器实例的方式.
有没有办法在SMO中重新启动所选实例?
解决方法
添加对System.ServiceProcess的引用.
using System.ServiceProcess; public static void RestartService(string sqlInstanceName) { if (string.IsNullOrEmpty(sqlInstanceName)) { throw new ArgumentNullException("sqlInstanceName"); } const string DefaultInstanceName = "MSsqlSERVER"; const string ServicePrefix = "MSsql$"; const string InstanceNameSeparator = "\\"; string serviceName = string.Empty; string server = sqlInstanceName; string instance = DefaultInstanceName; if (server.Contains(InstanceNameSeparator)) { int pos = server.IndexOf(InstanceNameSeparator); server = server.Substring(0,pos); instance = sqlInstanceName.Substring(pos + 1); } serviceName = ServicePrefix + instance; ServiceController sc = new ServiceController(serviceName,server); sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped,TimeSpan.FromSeconds(30)); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds(30)); }