When a VM is created from a template machine that has SQL Server installed, that SQL instance must be told that the machine name has changed.
If a “foo” machine is created from a template named “template”, the T-SQL statement run against the default SQL instance select @@SERVERNAME
returns “template” instead of the desired “foo”.
The solution is to execute the following T-SQL and then restart the SQL Server process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
select [@@SERVERNAME] = @@SERVERNAME go sp_helpserver --show config before go exec sp_dropserver 'template' go sp_addserver 'foo', local go sp_helpserver --show config after go ------------------------------------ --RESTART SQL INSTANCE AT THIS POINT ------------------------------------ select [@@SERVERNAME] = @@SERVERNAME go |
Here’s a C# version of the rename and the SQL Server process restart using PowerShell and the SqlDataClient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
/* imports using System.Management; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Data.SqlClient; */ //rename the default SQL server instance private void RenameSqlServer(string machineName, string uid, string pwd) { const string sql = @"if('{0}' <> @@servername) begin declare @sql nvarchar(max); begin try set @sql = 'sp_dropserver ''' + @@servername + '''' exec(@sql); end try begin catch declare @dummy bit end catch begin try set @sql = 'sp_addserver ''{0}'', local' exec(@sql); end try begin catch declare @dummy2 bit end catch end"; SqlConnection connection = null; try { var cb = new SqlConnectionStringBuilder() { DataSource = machineName, InitialCatalog = "master", UserID = uid, Password = pwd }; connection = new SqlConnection(cb.ToString()); connection.Open(); var command = new SqlCommand(string.Format(sql,machineName), connection); try { command.ExecuteNonQuery(); } catch { } connection.Close(); } finally { if (connection != null) connection.Close(); } } private void RestartSqlServer(string machineName) { const string script = @"$svc = get-service -ComputerName ""{0}"" -Name ""SQL Server (MSSQLSERVER)"" $svc.Stop() $svc.WaitForStatus('Stopped') #Write-Host Stopped $svc = get-service -ComputerName ""{0}"" -Name ""SQL Server (MSSQLSERVER)"" $svc.Start() $svc.WaitForStatus('Running') #Write-Host Running"; var sessionState = InitialSessionState.CreateDefault(); using (var ps = PowerShell.Create(sessionState)) { ps.Commands.Clear(); ps.AddScript(string.Format(script, machineName)); ps.Invoke(); } } |