Как изменить имя сервера sql server

При установке Microsoft SQL Server, внутреннее имя экземпляра SQL сервера создается на основании текущего имени хоста. Однако, при переименовании

При установке Microsoft SQL Server, внутреннее имя экземпляра SQL сервера создается на основании текущего имени хоста. Однако, при переименовании компьютера/сервера, имя SQL сервера в метаданных (хранится в sys.servers ) не обновляется автоматически, в результате чего при работе с SQL могут возникать разные проблемы. В этой инструкции мы покажем, как корректно обновить метаданные в SQL и изменить имя сервера без полной переустановки MSSQL. Инструкция применима для отдельно стоящего (не кластерного) SQL Server версий от MS SQL 2000 до 2012.

Совет. Можно сменить только имя севера, изменить имя экземпляра (инстанса) SQL Server без переустановки нельзя.

Откройте консоль SQL Server Management Studio и с помощью следующего запроса проверьте текущее имя хоста и имя инстанса SQL:

Select @@ServerName ServerName, Host_name() HostName

Как вы видите:

  • Имя сервера (HostName): DESKTOP-V2OE3P0
  • Полное имя экземпляра SQL (ServerName): DESKTOP-V2OE3P0SQLDB

Переименуем имя компьютер и перезагрузим его:

Rename-Computer -NewName Sql-Srv1 -Restart

Совет. Имя компьютера можно сменить и из свойств My Computer.

После перезагрузки попробуйте подключится к старому имени сервера SQL: DESKTOP-V2OE3P0SQLDB. Появится ошибка, ведь имя сервера изменилось.

Cannot connect to DESKTOP-V2OE3P0SQLDB.
A network-related or Instant-specific error occurred when establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interface, error: 26 – Error Locating Server/Instance Specified) (Microsoft SQL Server)

Еще раз проверим имя хоста и имя инстанса:

Select @@ServerName ServerName, Host_name() HostName

В данном случае имя инстанса не соответствует имени компьютера и ссылается на старое имя компьютера DESKTOP-V2OE3P0.

Чтобы изменить имя для именованного экземпляра SQL, выполните следующую команду TSQL.

Удалить старое имя:

sp_dropserver "DESKTOP-V2OE3P0SQLDB";
Go

Добавим новое имя:

sp_addserver "Sql-Srv1SQLDB", local;
GO


Если нужно сменить имя сервера у дефолтного экземпляра SQL Server команда такая:

sp_dropserver ″OldName″;
GO
sp_addserver ″NewName″, local;
GO

Дополнительные шаги

Если при выполнении команды sp_dropserver появится ошибка:

Msg 15190, Level 16, State 1, Procedure sp_dropserver, Line 56

Скорее всего, имеются удаленные подключения к серверу DESKTOP-V2OE3P0. Сбросить их можно такими командами. Для дефолтного инстанса:

sp_dropremotelogin DESKTOP-V2OE3P0;
GO

Для именованного:

sp_dropremotelogin DESKTOP-V2OE3P0SQLDB;
GO

Проверим, что имя сервера в метаданных обновилось:

SELECT @@SERVERNAME AS ‘ServerName’

SELECT * FROM SYS.SERVERS

Как вы видите, имя сервера изменилось. Осталось перезапустить службу SQL Server:

net stop MSSQL$SQLDB && net start MSSQL$SQLDB

Важно!

  • Этот способ подойдет только для переименования отдельностоящего SQL сервера. Для переименования SQL Server в кластере Failover Cluster нужно использовать консоль Cluster Management.
  • Нельзя изменить имя сервера, участвующего в репликации или зеркалировании
  • Если установлены службы отчетов Reporting services, после переименования они будут недоступны (https://msdn.microsoft.com/en-us/library/ms345235.aspx)

Переименование сервера с установленным MS SQL

Изменение имени компьютера с установленным экземпляром MS SQL Server — не самая хорошая идея, поскольку после переименования в работе SQL могут возникнуть некоторые проблемы. Чтобы избежать этих проблем, необходимо обновить системные метаданные таким образом, чтобы отобразить в них изменение имени компьютера.

Сделать это можно с помощью несложного SQL запроса. Так выглядит запрос для дефолтного экземпляра SQL Server:

sp_dropserver ″old_name″;
GO
sp_addserver ″new_name″, local;
GO

А так для именованного:

sp_dropserver ″old_nameInstanceName″;
GO
sp_addserver ″new_nameInstanceName″, local;
GO

Для примера возьмем компьютер с установленным экземпляром MS SQL Server.  Чтобы посмотреть текущее имя сервера, открываем SQL Management Studio и выполняем запрос:

select @@Servername

Как видите, имя сервера, полученное с помощью запроса (2012R2Std_Temp)  не совпадает с именем компьютера (SQL_Test).

вывод текущего имени

Поскольку в примере используется дефолтный экземпляр SQL Server, то для изменения имени выполним следующий запрос:

sp_dropserver ″2012R2Std_Temp″;
GO
sp_addserver ″SQL_Test″, local;
GO

переименование экземпляра SQL Server

После переименования необходимо перезапустить SQL Server. Сделать это можно из командной строки, командой:

net stop mssqlserver && net start mssqlserver

перезапуск сервиса

В заключение пара важных моментов, которые нужно учесть перед тем, как приступать к переименованию:

• Изменить можно только имя сервера, изменить имя экземпляра нельзя;
• Переименовать таким образом можно только отдельно стоящий сервер. Переименование SQL Server в отказоустойчивой конфигурации (Failover Cluster) производится из оснастки управления кластером;
• SQL Server не поддерживает переименование компьютеров, участвующих в репликации;
• Если сервер используется для зеркального отображения базы данных, то перед переименованием его необходимо отключить. После переименования зеркалирование необходимо заново настроить для нового имени;
• Если на компьютере установлены службы отчетов (Reporting services), то после переименования они могут быть недоступны. Подробнее здесь https://msdn.microsoft.com/en-us/library/ms345235.aspx.

My SQL server name contains dashes,so its not working properly.I want to rename the existing server name without dashes.
Is there anyway to rename sql server 2012 server name without dropping databases.

Thanks
Jamuna

asked Aug 22, 2015 at 9:09

4

Try below steps

First collect the output of the current instance configuration. You
can get the instance name stored in the SQL Server metadata.

Make sure you have backup of all the database if you are changing the
production server instance name.

sp_helpserver
select @@servername
You can change the instance name using below query. Default Instance

sp_dropserver 'old_name'
go
sp_addserver 'new_name','local'
go
Named Instance

sp_dropserver 'Server Nameold_Instance_name'
go
sp_addserver 'ServerNameNew Instance Name','local'
go
Verify sql server instance configuration by running below queries

sp_helpserver
select @@servername
Restart the SQL Server Services.

net stop MSSQLServer
net start MSSQLServer

A_Sk's user avatar

A_Sk

4,4623 gold badges25 silver badges51 bronze badges

answered Aug 22, 2015 at 9:25

Girish Jha's user avatar

Using Management studio
In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
Make sure that no one is using the database, and then set the database to single-user mode.
Expand Databases, right-click the database to rename, and then click Rename.
Enter the new database name, and then click OK.

Using Transact SQL

USE master;
GO
ALTER DATABASE AdventureWorks2012
Modify Name = Northwind ;
GO

answered Aug 22, 2015 at 9:17

Girish Jha's user avatar

1

Changing SQL Server Instance name is not a routine task. Although, sometimes we get requirements to change SQL Instance name. There are multiple scenarios in which we need to rename SQL Server Instance like:

  • If you have changed database server name then we should change SQL Server Instance name as well.
  • If you have cloned a database server from DBSERVER1 to DBSERVER2. Here, SQL Server installed on DBSERVER1 will be copied with same name to DBSERVER2. You need to change the SQL Server instance name on DBSERVER2.
  • Naming convention is not met.

Please keep in mind that we cannot change complete name of SQL Server named instance. Suppose you have installed a named instance SERVERNAMEDBInstance1 on your server. If you want to rename this named instance then we can only change first part of this name i.e. SERVERNAME. You cannot change DBInstance1 so your named instance will look like DBSERVERNAMEDBInstance1 post name change.

Impact of Changing SQL Server Instance Name

Rename SQL Server Instance name

We need to plan carefully before renaming any SQL Server Instance. Below is the list of possible impacts that you should go through while renaming SQL Server Instance name.

  • Those domain users who are accessing or connecting to the SQL Server Instance as part of Windows group will not be able to connect to renamed instance of SQL Server. Make sure to update the Windows group to specify the new computer name to establish connectivity to the SQL Server instance.
  • You would not be able to access reporting services after renaming the instance name. You should follow steps mentioned in attached article to rename SQL Server instance that is running with reporting services.
  • If you have database mirroring on the SQL Server instance then you need to drop the mirroring and then reconfigure it post renaming the SQL Server Instance.
  • Renaming SQL Server instance name does not support if your instance has replication, except when you use log shipping with replication.
  • You can change the name of SQL Server instance on secondary server in log shipping if the primary server is permanently lost.
  • If you have linked server configurations then it will be affected by the computer renaming operation. Use sp_addlinkedserveror sp_setnetname to update computer name references.

Rename SQL Server Instance

SQL Server instance name along with other system metadata stores in sys.servers system object. We need to update details in system metadata to reflect new name. Also i would suggest to not change SQL Server Instance name directly on your production server.

Suppose you have installed default instance of SQL Server in your database server. If you have changed the name of your database server then you need to update the name of default SQL Server instance as well in sys.servers system table. First, we need to drop the existing SQL Server instance name then we will add new name as per our choice. Follow below steps to change SQL Server instance name.

--Drop existing name
sp_dropserver [old_Instance_name]; 
GO 

--Update New name
sp_addserver [new_Instance_name], local; 
GO

If you have installed a named instance on your database server then you can run below command to change SQL Server Instance name.

sp_dropserver [old_nameinstancename]; 
GO 

sp_addserver [new_nameinstancename], local; 
GO

Note: Make sure to restart SQL Server services post running above commands to reflect these changes.

You can verify the changes by running below commands or by querying sys.servers system table. If you have not restarted SQL Server services then you might be getting older SQL Server instance name. So restart SQL Server service to apply new changes.

SELECT @@SERVERNAME

If you have remote logins on your database server then you might get error 15190 while running sp_dropserver command. Read below article to fix this issue and then proceed with the instance name change.

  • Fix Error 15190: There are still remote logins for the server

I hope you like this article. Please follow our Facebook and on Twitter handle to get latest updates.

Read More:

  • Configure Reporting Services After Renaming SQL Server Instance Name
  • How to Find When SQL Server was Installed on your database server?
  • What should be best value for fill factor in SQL Server?
  • Find all trace profilers running on SQL Server Instance
  • How to Move a Table to Another Filegroup?
  • Author
  • Recent Posts

Manvendra Deo Singh

I am working as a Technical Architect in one of the top IT consulting firm. I have expertise on all versions of SQL Server since SQL Server 2000. I have lead multiple SQL Server projects like consolidation, upgrades, migrations, HA & DR. I love to share my knowledge. You can contact me on my social accounts for any consulting work.

Manvendra Deo Singh

Summary

Article Name

How to Change SQL Server Instance Name?

Description

We need proper planning before renaming any SQL Server Instance. Read this article to get list of possible impacts that you should go through while renaming SQL Server Instance name. I have also explained how to change SQL Server instance name in step by step process.

  • Remove From My Forums
  • Question

  • Hi there

    I have installed SQL Server R2 on Windows Server 2008 R2 in a development environment.  The name of the server is SQL2008 and the instance name of the SQL Server is SQL2008DATA. Now, I wanted to change the server name to ‘earth’ so that the instance
    of SQL Server has to become ‘earth’, not ‘earthDATA’.

    I can change the Windows Server to ‘earth’. But to change the instance of SQL Server, I wanted to follow proper procedure so that I don’t break the SQL Server.

    Any ideas and help will be highly appreciated.

    Regards,

    Puskal

    • Edited by

      Tuesday, August 14, 2012 6:43 AM

Answers

  • Hi Puskal, the general recommendation is that you can change an instance name if it is the default instance (http://msdn.microsoft.com/en-us/library/ms143799.aspx
    ), but modifying an existing named instance is not recommended without uninstall/reinstall.  Your scenario is a bit tricky going from a named instance to renamed default instance.  You may want to install a default instance before renaming the machine,
    copy/migrate your DBs to the new instance, then follow the steps in the link to rename your default instance.  After that, you can uninstall your old instance to clean up.

    Thanks,
    Sam Lester (MSFT)


    My Blog

    This posting is provided «AS IS» with no warranties, and confers no rights. Please remember to click «Mark as Answer» and «Vote as Helpful» on posts that help you. This can be beneficial to other community members reading the thread.

    • Marked as answer by
      Shulei Chen
      Wednesday, August 22, 2012 9:53 AM

  • Hello Puskal,

    You would have to create the alias on every client machine, there is no kind of server based alias available, like a DNS alias for a machine.

    Start CliConfg.exe (part of MDAC, is on every machine installed) and goto tab «Alias», there you can create an aliase like «earth» pointing to «SQLServer2008DATA»


    Olaf Helper
    Blog
    Xing

    • Proposed as answer by
      Shulei Chen
      Tuesday, August 21, 2012 9:35 AM
    • Marked as answer by
      Shulei Chen
      Wednesday, August 22, 2012 9:53 AM

Понравилась статья? Поделить с друзьями:
  • Как изменить имя сервера myarena
  • Как изменить имя сервера linux
  • Как изменить имя сервера freebsd
  • Как изменить имя своей электронной почты на яндексе
  • Как изменить имя учетной записи стим