Ошибка 40 не удалось открыть подключение к sql серверу

TL;DR: Your SQL Server instance is using dynamic ports due to which it is not working. Force the SQL Server service to use static port # 1433 to get it working.

Detailed Explanation: Before starting with the details, let us first understand the scenario in which this issue can occur.

Whenever we run SQL Server setup on a machine then it asks us to input the name of the service instance. Why it asks for it? The reason is that the SQL Server setup provides a facility through which you can install and run multiple instances of SQL Server service on the same machine. There can be variety of reasons due to which you may want to run multiple SQL Server service instances on the same box e.g. unavailability of more physical servers in your estate, isolating SQL Server instance failures, load balancing, etc. To differentiate between multiple instances on the same machine, you must give a unique name to each service instance. Have a look at my machine (Refer screenshot). I have only one service instance and it is the default service instance of SQL Server:

enter image description here

For each new instance that you setup via SQL Server installer, there will be a new row in this service console window with same SQL Server prefix in the Name column. Text in parenthesis (MSSQLSERVER) is the name of the service instance. To understand the naming convention of SQL Server service instances, please refer to the corollary section in the end of the answer.

So, if you have more than one instance of SQL Server service running on a given machine then this problem can occur. When you have two or more than two SQL Server instances running on the same box then there are two possible configurations:

  1. Combination of default instance and one or more named instances
  2. Combination of two or more named instances only i.e. no default instance. SQL Server setup does not mandates the installation of default instance if you wish to. I had followed this configuration on my server when I faced this issue.

Key concept: Each instance of Microsoft SQL Server service installed on a machine uses a different port to listen for incoming SQL connection requests. In other words each SQL Server service is a different process which is attached to a unique port number. Default instance of SQL Server uses port # 1433. As you install named instances then they will start using dynamic ports which is decided at the time of start-up of Windows service corresponding to named SQL Server instance.

My code was failing (with error code 40) to connect to the only named SQL Server instance that I had on my VM. You can try below possible solutions:

Solution # 1: Client code trying to connect to SQL Server instance takes help from SQL Server browser service to figure out port number at which your named instance is listening for incoming connections. Make sure SQL browser service is running on your computer.

Solution # 2: Check the port # (in yellow color) your named SQL Server instance is using from SQL Server configuration manager as shown in the snapshot below:

enter image description here

Use that port number explicitly in your connection string or with sqlcmd shown below:

sqlcmd -s mymachinename,11380 -i deleteDB.sql -o SQLDelete.txt

Solution # 3: Force your named instance to use port # 1433 which is used by the default instance otherwise. Remember this solution will work only if you do not have any default SQL Server instance running on as machine as the port # 1433 would be already in use. In any operating system, a given port number can never be used by two processes at the same time. At the end of day, our SQL Server service instance is also a process.

Set TCP Dynamic ports field to blank and TCP Port field to 1433.

enter image description here

Change the port number in your connection string as shown below:

sqlcmd -s mymachinenameinstanceName -i deleteDB.sql -o SQLDelete.txt

OR

sqlcmd -s mymachinename,1433 -i deleteDB.sql -o SQLDelete.txt

Note: Please restart the SQL Server service instance after saving the TCP/IP settings.

Interestingly enough after resolving the error when I went back to dynamic port setting to reproduce the same error then it didn’t happen. Not sure why.

Please read below interesting threads to know more about dynamic ports of SQL Server:

How to configure SQL Server Port on multiple instances?

When is a Dynamic Port “dynamic”?

When to use a TCP dynamic port and when TCP Port?

I got leads to solution of my problem from this blog.

Corollary: Name of a SQL Server instance follows below mentioned logic

  1. For default instance, it is same as the name of the machine hosting the SQL Server service. It is predefined. It cannot be changed by the user during installation. Don’t get confused by the suffix (MSSQLSERVER) present in the service name. It is an internally managed name relevant for server side only. Client side apps will never get to know that.

  2. For named instance, it is a concatenated string in specific format as shown here — <name of the machine hosting the SQL Server service><user defined instance name>

    enter image description here

Pro Tip: Default SQL Server instance can be connected via few alias names as well which are convenient to type and intuitive to remember. But alias names can be used only while you are trying to connect to the service instance from the service host machine itself. In such a scenario, in place of host name you can also use below mentioned alias names:

  1. .
  2. (local)

While connecting to the SQL Server service instance from a remote machine only standard names will work.

Ошибка SQL Server 40 не удалось открыть соединение с sql server 2016

 Связанные с этим ошибки:

Ошибка 40 не удалось открыть соединение с sql server

поставщику именованных каналов не удалось открыть соединение с sql server 53

вызов поставщика sqlcmd с именем pipes provider ошибка 40 не удалось открыть соединение с sql server

поставщик именованных каналов не смог открыть соединение с SQL server 5 linked server

причины ошибок:

Эта ошибка возникает, когда SQL Server не может быть найден в Сети, что означает либо IP-адрес недоступен, либо номер TCP-порта либо не открыт, либо не является правильным номером порта, либо заблокирован брандмауэром и т. д

Решение:

Приведенные ниже шаги помогут устранить эти проблемы

1.Проверьте, можете ли вы пинговать сервер
2.Проверьте, открыт ли брандмауэр для подключения
3.Проверьте, работает ли служба SQL Server и если именованный экземпляр, то служба браузера
4.
Проверьте, включен ли протокол TCP / IP в диспетчере конфигурации SQL Server
5.Проверьте, установлен ли в свойствах SQL Server параметр “Разрешить удаленные подключения” на уровне экземпляра

Для экземпляра по умолчанию используется порт TCP / IP 1433, но это может быть изменено вручную. Поэтому пожалуйста проверьте TCP IP порт все еще находится на уровне по умолчанию 1433

Приветствую всех посетителей сайта Info-Comp.ru! Сегодня мы рассмотрим ситуацию, когда Вы пытаетесь подключиться к Microsoft SQL Server по сети, но Вам это не удаётся, так как возникает та или иная ошибка подключения.

В этом материале представлен последовательный план действий, который поможет Вам выявить и устранить причину возникновения таких ошибок подключения, и тем самым успешно подключиться к Microsoft SQL Server.

Не удается подключиться к Microsoft SQL Server по сети. Устраняем ошибку подключения

Итак, давайте начнем. Допустим, у нас есть Microsoft SQL Server, установленный на Windows, и мы будем пытаться подключится к нему по сети, например, из операционной системы Linux, используя Azure Data Studio.

Заметка! Как подключиться к Microsoft SQL Server из Linux.

В процессе подключения у нас возникает ошибка, и, чтобы ее устранить, мы будем последовательно выполнять определенные проверочные действия, которые помогут нам выявить причину этой ошибки.

Содержание

  1. Корректность ввода данных для подключения
  2. Доступность сервера по сети
  3. Открытые порты в брандмауэре
  4. Запущена ли служба «Обозреватель SQL Server»
  5. Запущена ли служба «SQL Server»
  6. Включен ли протокол «TCP/IP»
  7. Удаленные соединения с серверов
  8. Права имени входа, сопоставление с пользователем базы данных
  9. Подведение итогов

Корректность ввода данных для подключения

Первое, с чего необходимо начать, это, конечно же, с проверки данных для подключения, т.е. правильно ли мы указываем адрес сервера и имя экземпляра (если используется именованный экземпляр).

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

Имя экземпляра SQL Server необходимо указывать в тех случаях, когда у нас настроен именованный экземпляр, например, в редакции Express по умолчанию настраивается именованный экземпляр и динамические порты.

Если не указать имя экземпляра, когда это имя необходимо указывать, мы получим ошибку

«provider: TCP Provider, error: 40 – could not open a connection to SQL Server»

А если допустить ошибку в имени экземпляра, то

«provider: TCP Provider, error: 25 – connection string is not valid»

Поэтому лучше сразу проверить корректность ввода данных для подключения.

Скриншот 1

Заметка! Обзор инструментов для работы с Microsoft SQL Server.

Доступность сервера по сети

Если данные для подключения верны, то следующим шагом будет, конечно же, проверка доступности сервера, так как если сервер физически недоступен, то все следующие проверки будут абсолютно бесполезны и ни к чему не приведут.

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

«provider: TCP Provider, error: 25 – connection string is not valid»

Проверить доступность сервера можно стандартным способом, используя утилиту ping в командной строке.

Скриншот 2

Если сервер недоступен, то Вам необходимо настроить сеть, чтобы физический сервер, на котором располагается SQL Server, был доступен с компьютера, с которого Вы хотите подключиться.

Открытые порты в брандмауэре

Если сервер, на котором располагается SQL Server, физически доступен, то сразу же необходимо на нем проверить доступность портов в брандмауэре Windows, или в файрволе, который Вы используете.

Стандартный порт, на котором работает SQL Server, это 1433, соответственно, необходимо настроить правило для входящих подключений по порту 1433.

В случае если Вы используете именованный экземпляр SQL Server и динамические порты, то у Вас должно быть настроено правило для программы, в частности для исполняемого файла SQL Server – sqlservr.exe.

Для 2019 версии он расположен по следующему пути

Курс по SQL для начинающих

«C:Program FilesMicrosoft SQL ServerMSSQL15.MSSQLSERVERMSSQLBinnSqlservr.exe»

Кроме этого, в данном случае необходимо еще открыть UDP порт 1434 для службы «Обозреватель SQL Server».

Подробная официальная инструкция «Настройка брандмауэра Windows для доступа к SQL Server».

Продолжая тему именованных экземпляров и динамических портов, стоит отметить, что если используется именованный экземпляр и динамические порты, то дополнительно должна быть запущена служба «Обозреватель SQL Server». Если она не запущена, то подключиться Вы не сможете, будет возникать все та же ошибка

«provider: TCP Provider, error: 25 – connection string is not valid»

Поэтому запустите SQL Server Configuration Manager и проверьте соответствующую службу.

Скриншот 3

Запущена ли служба «SQL Server»

Если сервер физически доступен, необходимые порты открыты, то следующим шагом следует проверить, а запущена ли в принципе служба SQL Server.

Ведь бывает и такое, что мы пытаемся подключиться к SQL Server, а его просто нет, т.е. он даже не запущен.

Поэтому проверяем, запущена ли служба «SQL Server» в SQL Server Configuration Manager.

Скриншот 4

Заметка! Сравнение Azure Data Studio с SQL Server Management Studio (SSMS).

Включен ли протокол «TCP/IP»

Кроме всего вышеперечисленного необходимо проверить, включен ли протокол «TCP/IP» в сетевой конфигурации SQL Server, так как если SQL Server используется в сети, данный протокол обязательно должен быть включен.

Это можно проверить в SQL Server Configuration Manager в разделе «Сетевая конфигурация SQL Server».

Скриншот 5

Удаленные соединения с серверов

Также необходимо проверить, разрешены ли удаленные соединения с серверов. Это можно сделать в SQL Server Management Studio в свойствах сервера на вкладке «Соединения», параметр «Разрешить удаленные соединения с сервером» должен быть включен.

Скриншот 6

Заметка! Как включить нумерацию строк кода в SQL Server Management Studio.

Права имени входа, сопоставление с пользователем базы данных

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

«При входе пользователя TestLogin произошла ошибка».

Поэтому необходимо проверить, сопоставлено ли имя входа с пользователем базы данных и предоставлены ли необходимые права.

Это можно сделать в SQL Server Management Studio, перейдите в контейнер «Безопасность -> Имена для входа», выберите нужное имя входа и зайдите в свойства этого имени. Затем на вкладке «Сопоставление пользователей» отметьте базы данных, с которыми будет сопоставлено данное имя входа, и задайте необходимые права в виде указания ролей базы данных.

Скриншот 7

Подведение итогов

Таким образом, на основе всего вышеизложенного мы можем составить план действий, следуя которому мы обязательно определим и устраним причину возникновения ошибки подключения к Microsoft SQL Server по сети.

Что необходимо сделать для устранения ошибки подключения к Microsoft SQL Server по сети:

Проверить корректность ввода данных для подключения

Проверить доступность физического сервера по сети

Открыть порты в брандмауэре (файрволе)

Проверить, запущена ли служба «Обозреватель SQL Server»

Проверить, запущена ли служба «SQL Server»

Проверить, включен ли протокол «TCP/IP»

Проверить, разрешены ли удаленные соединения с серверов

Проверить права имени входа и сопоставить с пользователем базы данных

Заметка! Курсы по Transact-SQL для начинающих.

На сегодня это все, надеюсь, материал был Вам полезен, пока!

TL;DR; Your SQL Server instance is using dynamic ports which is not working. Force SQL Server to use static port # 1433.

Complete Details: First of all this problem is more likely if you’ve a mix of default and named instance or named instances only(which was my case).

Key concept: Each instance of Microsoft SQL Server installed on a computer uses a different port to listen for incoming connection requests. Default instance of SQL Server uses port # 1433. As you install named instances then they will start using dynamic ports which is decided at the time of start-up of Windows service corresponding to named SQL Server instance.

My code was failing (with error code 40) to connect to the only named SQL Server instance that I had on my VM. You can try below possible solutions:

Solution # 1: Client code trying to connect to SQL Server instance takes help from SQL Server browser service to figure out port number at which your named instance is listening for incoming connections. Make sure SQL browser service is running on your computer.

Solution # 2: Check the port # (in yellow color) your named SQL Server instance is using from SQL Server configuration manager as shown in the snapshot below:

enter image description here

Use that port number explicitly in your connection string or with sqlcmd shown below:

sqlcmd -s mymachinename,11380 -i deleteDB.sql -o SQLDelete.txt

Solution # 3: Force your named instance to use port # 1433 which is used by default instance. Remember this will work only if you don’t have any default SQL Server instance on your computer as the default SQL Server instance would be using using port # 1433 already. Same port number can’t be uses by two different Windows services.

Mark TCP Dynamic ports field to blank and TCP Port field to 1433.

enter image description here

Change the port number in your connection string as shown below:

sqlcmd -s mymachinenameinstanceName -i deleteDB.sql -o SQLDelete.txt

OR

sqlcmd -s mymachinename,1433 -i deleteDB.sql -o SQLDelete.txt

Note: Every change in TCP/IP settings requires corresponding Windows service restart.

Interestingly enough after resolving the error when I went back to dynamic port setting to reproduce the same error then it didn’t happen. Not sure why.

Please read below interesting threads to know more about dynamic ports of SQL Server:

How to configure SQL Server Port on multiple instances?

When is a Dynamic Port “dynamic”?

When to use a TCP dynamic port and when TCP Port?

I got leads to solution of my problem from this blog.

TL;DR; Your SQL Server instance is using dynamic ports which is not working. Force SQL Server to use static port # 1433.

Complete Details: First of all this problem is more likely if you’ve a mix of default and named instance or named instances only(which was my case).

Key concept: Each instance of Microsoft SQL Server installed on a computer uses a different port to listen for incoming connection requests. Default instance of SQL Server uses port # 1433. As you install named instances then they will start using dynamic ports which is decided at the time of start-up of Windows service corresponding to named SQL Server instance.

My code was failing (with error code 40) to connect to the only named SQL Server instance that I had on my VM. You can try below possible solutions:

Solution # 1: Client code trying to connect to SQL Server instance takes help from SQL Server browser service to figure out port number at which your named instance is listening for incoming connections. Make sure SQL browser service is running on your computer.

Solution # 2: Check the port # (in yellow color) your named SQL Server instance is using from SQL Server configuration manager as shown in the snapshot below:

enter image description here

Use that port number explicitly in your connection string or with sqlcmd shown below:

sqlcmd -s mymachinename,11380 -i deleteDB.sql -o SQLDelete.txt

Solution # 3: Force your named instance to use port # 1433 which is used by default instance. Remember this will work only if you don’t have any default SQL Server instance on your computer as the default SQL Server instance would be using using port # 1433 already. Same port number can’t be uses by two different Windows services.

Mark TCP Dynamic ports field to blank and TCP Port field to 1433.

enter image description here

Change the port number in your connection string as shown below:

sqlcmd -s mymachinenameinstanceName -i deleteDB.sql -o SQLDelete.txt

OR

sqlcmd -s mymachinename,1433 -i deleteDB.sql -o SQLDelete.txt

Note: Every change in TCP/IP settings requires corresponding Windows service restart.

Interestingly enough after resolving the error when I went back to dynamic port setting to reproduce the same error then it didn’t happen. Not sure why.

Please read below interesting threads to know more about dynamic ports of SQL Server:

How to configure SQL Server Port on multiple instances?

When is a Dynamic Port “dynamic”?

When to use a TCP dynamic port and when TCP Port?

I got leads to solution of my problem from this blog.

TL;DR; Your SQL Server instance is using dynamic ports which is not working. Force SQL Server to use static port # 1433.

Complete Details: First of all this problem is more likely if you’ve a mix of default and named instance or named instances only(which was my case).

Key concept: Each instance of Microsoft SQL Server installed on a computer uses a different port to listen for incoming connection requests. Default instance of SQL Server uses port # 1433. As you install named instances then they will start using dynamic ports which is decided at the time of start-up of Windows service corresponding to named SQL Server instance.

My code was failing (with error code 40) to connect to the only named SQL Server instance that I had on my VM. You can try below possible solutions:

Solution # 1: Client code trying to connect to SQL Server instance takes help from SQL Server browser service to figure out port number at which your named instance is listening for incoming connections. Make sure SQL browser service is running on your computer.

Solution # 2: Check the port # (in yellow color) your named SQL Server instance is using from SQL Server configuration manager as shown in the snapshot below:

enter image description here

Use that port number explicitly in your connection string or with sqlcmd shown below:

sqlcmd -s mymachinename,11380 -i deleteDB.sql -o SQLDelete.txt

Solution # 3: Force your named instance to use port # 1433 which is used by default instance. Remember this will work only if you don’t have any default SQL Server instance on your computer as the default SQL Server instance would be using using port # 1433 already. Same port number can’t be uses by two different Windows services.

Mark TCP Dynamic ports field to blank and TCP Port field to 1433.

enter image description here

Change the port number in your connection string as shown below:

sqlcmd -s mymachinenameinstanceName -i deleteDB.sql -o SQLDelete.txt

OR

sqlcmd -s mymachinename,1433 -i deleteDB.sql -o SQLDelete.txt

Note: Every change in TCP/IP settings requires corresponding Windows service restart.

Interestingly enough after resolving the error when I went back to dynamic port setting to reproduce the same error then it didn’t happen. Not sure why.

Please read below interesting threads to know more about dynamic ports of SQL Server:

How to configure SQL Server Port on multiple instances?

When is a Dynamic Port “dynamic”?

When to use a TCP dynamic port and when TCP Port?

I got leads to solution of my problem from this blog.

Named Pipes Provider, error: 40 — Could not open a connection to SQL Server :

I.   Incorrect connection string, such as using SqlExpress.

Check out: http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=558456&SiteID=17

                https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1245564&SiteID=1

The typical error when dealing with Express includes:

a.  User is not aware of SqlExpress was installed as a named instance, consequently, in his/her connection string, he/she only specify «.»,»localhost» etc instead of «.SqlExpress» or «<machinename>Sqlexpress».

b. Np was disabld by default after installing SqlExpress.

c. If Sqlexpress was installed on the remote box, you need to enable remote connection for Express.

Please read the following blog for best practice of connecting to SqlExpress.

http://blogs.msdn.com/sql_protocols/archive/2006/03/23/558651.aspx

II. Named Pipes(NP) was not enabled on the SQL instance.

Check out: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=136253&SiteID=1

Oppose to SQL 2000 which turn on all protocols, SQL 2005 SKUs turn off NP by default. So, when you see this error, please check:

1) Go to SQL Server Configuration Manager, See Server has NP enabled.

2) %windir%program filesmicrosoft sql servermssql.1mssqllog, notepad ERRORLOG, see whether Server is listening on NP.  You should see «Server named pipe provider is ready to accept connection on [ .pipesqlquery ] or [.pipemssql$<InstanceName>sqlquery]»

3) Notice that «sqlquery» is the default pipe name, so you need to know server is listening on which pipe name. eg: if you specify server pipe name is «sqlquery1», then you would see in the errorlog that server listening on [ .pipesqlquery1 ], and go to SQL Server Configuration Manager, click client Named Pipe properties, see whether the pipe name is same with the one server listening on.

4) If you are using SQL Native Client ODBC/OLEDB provider({SQL Native Client} or SQLNCLI), go to SQL Configuration Manager, click client protocols, make sure NP and TCP are both enabled. Right click properties of NP, make sure client is using the same pipe name as server for connection.

5) If you are using MDAC ODBC/OLEDB({SQL Server} or SQLOLEDB) provider, in command line, launch «cliconfg.exe» and make sure NP enabled and right pipe name specified.

III. Remote connection was not enabled. 

Check out: when you right click on the Server in SQL Server Management Studio, in Connections, the Remote server connections part, you have enabled the «Allow remote connections to this server» check box

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=322792&SiteID=1

https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=763875&SiteID=1

If you are making a remote connection, namely, your target SQL Server is on the different box as client application, you might need to check whether:

a. «File and Printer Sharing» was opened in Firewall exception list.

b. Please see the blog for enabling remote connection for express and troubleshooting tips of remote connection.

http://blogs.msdn.com/sql_protocols/archive/2005/11/14/492616.aspx

http://blogs.msdn.com/sql_protocols/archive/2006/09/30/SQL-Server-2005-Remote-Connectivity-Issue-TroubleShooting.aspx

IV. Server not started, or point to not a real server in your connection string.

Check out: Open SQL Server Surface Area Configuration and ensure all the required services are started, Remote Connections are configured.

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=348662&SiteID=1

a. use «sc query mssqlserver» for default instance or «sc query mssql$<instancename>» to make sure SQL Server was started. Sometimes, reseason behind the broken of your client application w/ this error:40 might be SQL server restarted and failed, so, it’d better for you to double check.

b. User specified wrong server in their connection string, as described in the forum discussion, «MSSQLSERVER» is an invalid instance name. Remember, when you connect to default instance, <machinename> could be best representitive for the instance, when you connect to a named instance such as sqlexpress, you should specify <machinename><instancename> as data source in your connection string.

 V. Other reasons such as incorrect security context.

Check out: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=192622&SiteID=1

Such error also occured during user operation such as moving database or db mirroring or cluster, any DB OP that might invovle different sql instances, namely, the destination database is located in another sql instance and user is not aware of the state of the destination. I recommend you first isolate whether this fail is during connection stage or data operation stage.

a. During data operation, you are normally asked to type in the destination server name whether it is default to «(local)» or another server «<remotemachinename>». So, remember the exact string that represent the target instance, then when the error repros, open command line, use «sqlcmd -S<representitive> -E» ,see what happens, if the connection fail, please follow up above I — IV troubleshooting lists. otherwise continue.

b. If you can make basic conection, but still face the error, then there must be something that server reject the connection or client close the connection for some reason.

VI. Please try basic connectivity tests between the two mahcines you are working on. One simple way to verifty connectivity is to use command line tools, such as osql.exe. For example, osql -E -StcpTongue Tiedervernameinstancename. If it connects cross-machine successfully, please also verify that your connection string in your scenario is correct.

Here are some blogs which could be helpful: just follow the basic connectivity troubleshooting guidelines on the SQL Protocols blog, see:

SQL Server 2005 Connectivity Issue Troubleshoot — Part I

http://blogs.msdn.com/sql_protocols/archive/2005/10/22/483684.aspx

and

SQL Server 2005 Connectivity Issue Troubleshoot — Part II

http://blogs.msdn.com/sql_protocols/archive/2005/10/29/486861.aspx

Hope this helps.

Check the following article:


If you get the following SQL Server Error:

“A network-related or instance-specific error occurred while 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 Interfaces, error: 26 — Error Locating Server/Instance Specified) ”

Things to check:

1. Make sure your database engine is configured to accept remote connections• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
• Click on Surface Area Configuration for Services and Connections
• Select the instance that is having a problem > Database Engine > Remote Connections
• Enable local and remote connections
• Restart instance

2. Check the SQL Server service account• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding

3. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb
P.NET application
• Usually the format needed to specify the database server is machinenameinstancename
• Check your connection string as well

<connectionStrings>

<add name=»SampleConnectionString» connectionString=»Data Source=machinenameinstancename;Initial Catalog=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max
Pool Size=60;Connect Timeout=30″ providerName=»System.Data.SqlClient»/>

</connectionStrings>

4. You may need to create an exception on the firewall for the SQL Server instance and port you are using• Start > Run > Firewall.cpl
• Click on exceptions tab
• Add the sqlservr.exe (typically located in C:Program Files (x86)Microsoft SQL ServerMSSQL.xMSSQLBinn, check your installs for the actual folder path), and port (default is 1433)
• Check your connection string as well

5. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings

6. Check SQLBrowser; check that it is running. You
may also need to create an exception in your firewall for SQLBrowser.

7. Check that you have connectivity to the SQL Server. 

Note what you are using to connect: machine name, domain name or IP address? Use this when checking connectivity. For example if you are using myserver
• Start > Run > cmd
•netstat -ano| findstr 1433
•telnet myserver 1433
•ping -a myserver

Check what ports are IP addresses are being returned.


Regards,

Basit A. Farooq (MSC Computing, MCITP SQL Server 2005 & 2008, MCDBA SQL Server 2000)

http://basitaalishan.com

Please remember to click «Mark as Answer» on the post that helps you, and to click
«Unmark as Answer» if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Marked as answer by
    Maggie Luo
    Monday, January 21, 2013 3:02 PM

Check the following article:


If you get the following SQL Server Error:

“A network-related or instance-specific error occurred while 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 Interfaces, error: 26 — Error Locating Server/Instance Specified) ”

Things to check:

1. Make sure your database engine is configured to accept remote connections• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
• Click on Surface Area Configuration for Services and Connections
• Select the instance that is having a problem > Database Engine > Remote Connections
• Enable local and remote connections
• Restart instance

2. Check the SQL Server service account• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding

3. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb
P.NET application
• Usually the format needed to specify the database server is machinenameinstancename
• Check your connection string as well

<connectionStrings>

<add name=»SampleConnectionString» connectionString=»Data Source=machinenameinstancename;Initial Catalog=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max
Pool Size=60;Connect Timeout=30″ providerName=»System.Data.SqlClient»/>

</connectionStrings>

4. You may need to create an exception on the firewall for the SQL Server instance and port you are using• Start > Run > Firewall.cpl
• Click on exceptions tab
• Add the sqlservr.exe (typically located in C:Program Files (x86)Microsoft SQL ServerMSSQL.xMSSQLBinn, check your installs for the actual folder path), and port (default is 1433)
• Check your connection string as well

5. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings

6. Check SQLBrowser; check that it is running. You
may also need to create an exception in your firewall for SQLBrowser.

7. Check that you have connectivity to the SQL Server. 

Note what you are using to connect: machine name, domain name or IP address? Use this when checking connectivity. For example if you are using myserver
• Start > Run > cmd
•netstat -ano| findstr 1433
•telnet myserver 1433
•ping -a myserver

Check what ports are IP addresses are being returned.


Regards,

Basit A. Farooq (MSC Computing, MCITP SQL Server 2005 & 2008, MCDBA SQL Server 2000)

http://basitaalishan.com

Please remember to click «Mark as Answer» on the post that helps you, and to click
«Unmark as Answer» if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Marked as answer by
    Maggie Luo
    Monday, January 21, 2013 3:02 PM

Problem

Unable to save template after making changes.

Symptom

Error message when attempting to hit save:

Template [Document] failed to save in DR
.
Problem description
Clarity.10026 Template [Document] failed to save.

System.Data.SqlClient.SqlException A network-related or instance-
specific error occurred while 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: Named Pipes Provider, error: 40 — Could
not open a connection to SQL Server)

Cause

The cause for this issue is that the cube’s relational connection source is pointing to a relational database on a separate server environment.

Diagnosing The Problem

Reconfirm all connection/detail to ensure that both the relational database and olap cube connection strings are from the same server.

— Open up Analysis Services

— Select the database that is being used and expand

— Select Data Sources, and further expand.

— Select the datasource and right click and select properties.

— Examine the Connection String information to see if the relational database used is on the same server as Analysis Services.

Resolving The Problem

In this case, the issue lies in the connection string for the cube. Analysis Services was on one server and the corresponding relational database was on another. The customer forgot to repoint the database after moving the database from a production environment.

Edit the connection string to use the same server as the Analysis Service and this should correct the problem.

If the databases are required to be on separate servers, please refer to technote # 1583743

[{«Product»:{«code»:»SSMVH7″,»label»:»Clarity 7″},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»—«,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.2.1;7.2;7.0;6.2;6.1;6.0″,»Edition»:»Standard»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

SOLVED !!
Simply, Instead of using «Microsoft SQL Server (SqlClient)» as The DataSource
Use «.NET Framework Data Provider for MySQL»
Use your Credentials for the MySQL Connection (ServerName,User,Password,DB-Optional)
It should work now.

I’ve used ADO Entity DATA Model Wizard for My Project and configure .Net as My DataSource.
If you have the «error 40…» in different occausion verify your DataSource to the right one.

I tried like most of you to look for Firewall settings, server settings,
but it was simple than i thought, so check it out…

For download —>.NET Framework Data Provider for MySQL as your data source/provider:

http://dev.mysql.com/get/Downloads/Connector-Net/mysql-connector-net-6.7.4.msi

It worked for me !

Понравилась статья? Поделить с друзьями:
  • Ошибка 40 на электросамокате kugoo s1 как исправить
  • Ошибка 40 floppy disk failed
  • Ошибка 4 цилиндра на субару
  • Ошибка 4 цилиндра киа рио
  • Ошибка 4 цилиндра гольф 6