finding the correct connection string for a local SQL instance - sql-server

I'm trying to build a connection string for a test environment that will connect to the local SQL Server instance on different machines. The purpose of this is so that a developer can checkout the code from TFS, build it, and run the testcases, connecting to his local DB. The problem is that different developer's machines may have different SQL Server setups. In particular, some may be running the full server, others may be running SQL Server Express.
I'm trying to right a utility routine that will take template connection string (e.g., Data Source=(local); Initial Catalog= myDB; Integrated Security=SSPI;) and modify the Data Source to work with the local server.
I've tried using SmoApplication.EnumAvailableServers() (returns an empty table, regardless of whether I user true or false parameters), and SqlDataSourceEnumerator.GetDataSources() (returns 2888 servers from the network, but none on the local machine), SQLCMD -L (returns nothing).
Any suggestions?
In the alternative, is there an easy way to tell whether a particular connection string will connect to a server (without waiting for it to timeout if it doesn't). If I could find the answer to that, I could try the likely suspects until I got one to work.

you might try to get the connection string as following:
Create a new blank file and name it test.udl.
Double click on it, and a "Data Link Properties" dialog should appear.
On "Providers" tab, select "Microsoft OLE DB Provider for SQL Server" or "SQL Native Client"
On "Connections" tab, try various settings and use the "Test Connection" button to test them. Click "Ok" when it works.
Open the test.udl file in Notepad and copy the line that starts with "Provider=" into your Web.config "ConnectionString" value, BUT delete the little part that says "Provider=SQLNCLI.1;"

If you want each developer to work with their own local SQL server, then the ADO connection string should have the Data Source set to localhost
... ; Data Source=localhost; ...
Additionally, to get a list of current servers, go to the command line and run
osql -L

You can look in the registry to find all local SQL Server instances. This key contains the list: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL.
Each named instance will have a value in this key. For named instances the name of the value is the same as the name of the instance. For the default instance the value will be named MSSQLSERVER.

This will do the trick:
Data Source=.\SQLEXPRESS

Related

Connecting to SQL Server in a remote server from Access

We have a Server A and a Server B.
In Server A we have our ERPs made in Access and VBA.
In Server B we have an instance of SQL Server that needs to stay in that server.
Some Access databases need to link to some tables from that SQL Server instance and I don't want the password to be stored in the MSysObjects table, so I cannot manually link the tables checking the save the connection option.
I saved the connection string in a table with password obfuscation. With that connection string I re-link the tables on startup.
The instance is accessed through it's IP, not the name of the instance. If I use the name of the instance it doesn't work.
It works for me but not for other users except one.
The SQL Server instance has been properly configured to allow remote connections, the ports have been opened and rules added to firewall. If it wasn't properly configured it wouldn't work for me and the other user, so I'm pretty confident in that. The same with the connection string and the methods to stablish the connection in Access.
What I've tried:
Installing the SQL Native Client 11.0.
Installing a full SQL Server Express.
Configured the SQL Browser service to star automatically instead of being disabled.
Step 1 did not work for any user. Step 2 did work for one user but not for the rest. Step 3 did not had any effect. For me I had it installed in my machine since forever, so it doesn't apply.
If I try to do the same with a SQL Server instance in our LAN it works for every user, but not when the instance is in a remote server.
Note I have limited knowledge. Maybe I say something that does not make sense.
Ok, a few things:
Installing the SQL Native Client 11.0.
Ok, then you have to re-link the tables - choose the new driver. A refresh of the linked tables is NOT sufficent. And this ALSO means that each work station ALSO now must have native 11 instlled. And if you say decide to link using native 17 (a much newer odbc driver), then AGAIN YOU must install this native driver on each work station. While you can install multiple sql drivers on each workstation, the driver you used to link the tables MUST ALSO be installed and exist on each work station.
Installing a full SQL Server Express.
Why? What would installing a copy of sql server have to do with OTHER sql servers on other machines that you are attempting to connect to? You think installing sql server on a machine effects the sql server running say on amazon.com? So, this move makes no sense at all.
You are attempting to connect to some instance of sql server running on some other computer. Makes no sense nor will it help to install some copy of sql server that you not using, not connecting to, and that has zero to do with this issue.
Configured the SQL Browser service to star automatically instead of being disabled.
Where? The browser service is set to run and startup on the server and SAME machine where sql server is installed and running. So, yes, without question, those two sql servers A, and B most certainly MUST have the sql browser service running. That service is what allows the client computers to connect to that running instance of sql server. In the past, older (previous) versions of sql server would allow a default connection, but now in near all cases, you MUST ensure that the sql browser service is running on that computer that also has the database you are attempting to connect to.
it's worth to note that the instance is accessed through it's IP, not the name of the instance.
No, you likly have this incorrect. There are two part.
The server name - and then the "instance" of sql server running.
While you can swap out (not use) the server name, you STILL WILL NEED to specify the sql server instance.
So, you can use this format:
myservername\SQLEXPRESS
Or, you can replace the server with a IP address, but you STILL NEED the sql server instance. (by default, it is SQLEXPRESS - but you have to check what the instance of sql server database is).
192.168.1.30\SQLEXPRESS
So while you can use IP or server name - it is often more reliable to use the IP address, but that does NOT get you off the hook from having to specify the sql instance you connect to. Again, previous editions of sql server often allowed a "default" instance, and you did not in general have to specify the "instance", but now you do. And to be double clear, when using such a instance, that sql server needs to be running the sql browser service. (in fact, the browser service is what translates the incoming request to the given and correct instance of sql server).
I DON'T want the password to be stored in the MSysObjects table,
You don't have to, and in fact should NOT include the uid/password in your connection string. And in fact ZERO reason exists to do so.
What you do is execute a one time logon, and THEN link the tables without UID/password. This is not only a great idea, but it also means that your uid/password is not included in the connection strings, but also means users can't get at, or even by accident see/get the uid/password.
It also means that say someone where to launch a copy of access, and import the linked tables from this applcation. When they attempt to use the linked tables, they will NOT work.
So, then how do linked tables work without a password? (and this ALSO by the way saves you from having to re-link tables on startup!!!).
The way this works, is you in code execute a one time logon to the server on startup. That means you can either:
Prompt the user for their sql UID/password.
or
Have in code, the uid/password. (or perhaps in a text file y ou read on startup. You can thus hide, or encrypt or whatever for that uid/passwords.
Then in your startup code, you execute a one time logon. Once you done this, then all linked tables will now work - and work without having uid/password.
since you have two servers then you need to execute two logons, one for server A, and one for server B. But, once again, as long as the linked tables exist, then they will work.
Now, there are "longer" articles on how to use this logon idea, and then not have to include, or re-link your tables for the SQL uid/password.
The basic code to execute a logon is like this:
Function TestLogin(strCon As String) As Boolean
On Error GoTo TestError
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("")
qdf.connect = strCon
qdf.ReturnsRecords = False
'Any VALID SQL statement that runs on server will work below.
' this does assume user has enough rights to query built in
' system tables
qdf.sql = "SELECT 1 "
qdf.Execute
TestLogin = True
Exit Function
TestError:
TestLogin = False
Exit Function
End Function
Keep in mind, that ONCE you acheived a legal logon, then EVEN addtional logon attempts will return true.
Not usually a big deal, but this means you supply a valid connection to above, and if it logs on and works - then now all your linked tables (without uid/password) will work.
I note the above issue that ONCE you done the logon, then all 2nd or more times running the above will work (even if bad or incorrect!!! - DO NOT forget this tip!!!). (this can confuse the daylights out of a developer, since they execute logon, (or open a table). Then they test above routine with a BAD uid/passwords, and it works!!!
So, you have to EXIT access to clear out the password cache - no other way.
So, keep the above tips in mind.

Share Excel file with SQL Server connection on network

I have an Excel file with a SQL query to retrieve information from our SQL Server database. I want this Excel file to be available to anyone on the network.
I tested this a couple of times and it is not creating the connection on any PC but mine. I found a few answers that I thought would resolve the problem but whenever I attempt to change the connection string in Excel it reverts back to the original string.
Here is the current connection string:
DRIVER=SQL Server;SERVER=SERVER\SQLEXPRESS;UID=<My User ID>;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=<My WS ID>;DATABASE=<Database Name>
The main person I would like to have access to this file also has permissions to access the database from SQL Server Management Studio. What I found from searching said I should set the security to Windows Authentication and change the connection string to something along these lines:
DRIVER=SQL Server;SERVER=SERVER\SQLEXPRESS;Integrated Security=SSPI ;DATABASE=<Database name>
However when I attempt to change the connection settings in my Excel file it reverts back to the original string. What would be causing it to revert back to the original connection string after I change it and is the second example correct?
Thanks in advance
I'll leave the question open since it could help someone else down the road. I got this to work by changing the connection string inside of the connection file to:
DRIVER=SQL Server;SERVER=SERVER\SQLEXPRESS;Integrated Security=SSPI ;DATABASE=<Database name>
The line Integrated Security=SSPI took care of the sharing issues between computers.

SERVERPROPERTY('SERVERNAME') v/s 'localhost'

I am using SQL Server 2008 R2.
I have created an SQL Job that fetches data from database tables and writes it to output file i.e. CSV on specific location.
For this I am using bcp and xp_cmdshell.
In bcp I need to pass the server name. Upto this I was using 'localhost' as server name, but by running this on another PC I have came to know that the 'localhost' login is not working on it so that the output files are not getting generated.
I searched about it and got another command that returns the server name along with server instance. i.e. SERVERPROPERTY('ServerName')
Now I am confused for using it. It is running OK with my local PC and Another PC also but my question is - Is it always run safely without any error if I put it on any other Server or PC? Which one of this is advisable to be used?
I think you're getting confused about the term "LocalHost". This is just an alias (aka loopback) that points back to the machine originating the connection.
For example, if my machine was named MYMACHINE and I was running a default instance on it, I could connect to the database either by specifying LocalHost or MYMACHINE and I would connect. If someone else was trying to connect from machine YOURMACHINE, they would only be able to connect to my database if they specified MYMACHINE. If they entered LOCALHOST it would try to connect to YOURMACHINE as that is where the connection is originating.
Back to your question now, yes, it is safe to get the servername value from SERVERPROPERTY('ServerName') as it will always report the correct and current network name of the server. This is not the case with ##SERVERNAME, so you should shy away from that for your purposes.
LocalHost: https://en.wikipedia.org/wiki/Localhost
##ServiceName (last paragraph of remarks section is important): http://msdn.microsoft.com/en-us/library/ms187944.aspx
P.S. I apologize for not adding a comment to the question, but my reputation is not currently high enough to do so.

How do I setup OLEDB to connect to a remote database?

I am locally running an Oracle 11g database. I have a small program connecting to it in code via OLEDB in VC++ (It only runs some database tests, I'm making sure I have all the basics down before I go into the real thing.) The connection information in code only includes the provider, instance name, user name, and password. All this aspect works fine.
//For example, both these ways of connecting work:
result = dataSource.Open(DATABASE_PROVIDER, DATABASE_NAME,
DATABASE_USER_NAME, DATABASE_USER_PASSWORD);
result = dataSource.OpenFromInitializationString(L"Provider=OraOLEDB.OracleDataSource=orcl;User ID=SYSTEM;Password=admin;");
I now want to send this program to other computers in my network and run it from there, connecting to my database on my local machine.
How would I go about connecting the other computers to my database in a way that the code will understand?
I have been trying to connect locally via IP instead of "localhost", figuring I could then simply use the same code and client. In that regard, I have tried a few things without success:
-I have tried modifying the connection string to change "Data Source" to my IP, but it could not connect.
-I have tried adding some parameters from other connection string examples I had seen, but they were not for Oracle and were ignored.
-I have also tried modifying tnsnames.ora and listener.ora to change local host to an IP address, but I know that didn't work, as it would still connect if I entered rubbish.
Anyone has the knowledge to help out?
For an Oracle db, you should set up a new tnsnames entry on their individual machines that points to your local db. Then use that new tns name as the datasource. You'll also need to make sure that your local db instance is accessible to them in the first place. (This is not enabled by default in Oracle Express, by the way.)
I've also generally had more success using msdaora as the data provider instead of OraOLEDB.

How can I determine installed SQL Server instances and their versions?

I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.
At a command line:
SQLCMD -L
or
OSQL -L
(Note: must be a capital L)
This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this...
At command line:
svrnetcn
In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.
You could query this registry value to get the SQL version directly:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ClientSetup\CurrentVersion
Alternatively you can query your instance name and then use sqlcmd with your instance name that you would like:
To see your instance name:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names
Then execute this:
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
If you are using C++ you can use this code to get the registry information.
All of the instances installed should show up in the Services Snap-In in the Microsoft Management Console. To get the instance names, go to Start | Run | type Services.msc and look for all entries with "Sql Server (Instance Name)".
-- T-SQL Query to find list of Instances Installed on a machine
DECLARE #GetInstances TABLE
( Value nvarchar(100),
InstanceNames nvarchar(100),
Data nvarchar(100))
Insert into #GetInstances
EXECUTE xp_regread
#rootkey = 'HKEY_LOCAL_MACHINE',
#key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
#value_name = 'InstalledInstances'
Select InstanceNames from #GetInstances
I know this thread is a bit old, but I came across this thread before I found the answer I was looking for and thought I'd share. If you are using SQLExpress (or localdb) there is a simpler way to find your instance names.
At a command line type:
> sqllocaldb i
This will list the instance names you have installed locally. So your full server name should include (localdb)\ in front of the instance name to connect. Also, sqllocaldb allows you to create new instances or delete them as well as configure them. See: SqlLocalDB Utility.
If you just want to see what's installed on the machine you're currently logged in to, I think the most straightforward manual process is to just open the SQL Server Configuration Manager (from the Start menu), which displays all the SQL Services (and only SQL services) on that hardware (running or not). This assumes SQL Server 2005, or greater; dotnetengineer's recommendation to use the Services Management Console will show you all services, and should always be available (if you're running earlier versions of SQL Server, for example).
If you're looking for a broader discovery process, however, you might consider third party tools such as SQLRecon and SQLPing, which will scan your network and build a report of all SQL Service instances found on any server to which they have access. It's been a while since I've used tools like this, but I was surprised at what they found (namely, a handful of instances that I didn't know existed). YMMV. You might Google for details, but I believe this page has the relevant downloads: http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx
SQL Server permits applications to find SQL Server instances within the current network. The SqlDataSourceEnumerator class exposes this information to the application developer, providing a DataTable containing information about all the visible servers. This returned table contains a list of server instances available on the network that matches the list provided when a user attempts to create a new connection, and expands the drop-down list containing all the available servers on the Connection Properties dialog box. The results displayed are not always complete.
In order to retrieve the table containing information about the available SQL Server instances, you must first retrieve an enumerator, using the shared/static Instance property:
using System.Data.Sql;
class Program
{
static void Main()
{
// Retrieve the enumerator instance and then the data.
SqlDataSourceEnumerator instance =
SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
// Display the contents of the table.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayData(System.Data.DataTable table)
{
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
}
from msdn http://msdn.microsoft.com/en-us/library/a6t1z9x2(v=vs.80).aspx
One more option would be to run SQLSERVER discovery report..go to installation media of sqlserver and double click setup.exe
and in the next screen,go to tools and click discovery report as shown below
This will show you all the instances present along with entire features..below is a snapshot on my pc
SQL Server Browser Service http://msdn.microsoft.com/en-us/library/ms181087.aspx
This query should get you the server name and instance name :
SELECT ##SERVERNAME, ##SERVICENAME
If you are interested in determining this in a script, you can try the following:
sc \\server_name query | grep MSSQL
Note: grep is part of gnuwin32 tools
From Windows command-line, type:
SC \\server_name query | find /I "SQL Server ("
Where "server_name" is the name of any remote server on which you wish to display the SQL instances.
This requires enough permissions of course.
I had the same problem. The "osql -L" command displayed only a list of servers but without instance names (only the instance of my local SQL Sever was displayed).
With Wireshark, sqlbrowser.exe (which can by found in the shared folder of your SQL installation) I found a solution for my problem.
The local instance is resolved by registry entry. The remote instances are resolved by UDP broadcast (port 1434) and SMB.
Use "sqlbrowser.exe -c" to list the requests.
My configuration uses 1 physical and 3 virtual network adapters.
If I used the "osql -L" command the sqlbrowser displayed a request from one of the virtual adaptors (which is in another network segment), instead of the physical one.
osql selects the adpater by its metric. You can see the metric with command "route print".
For my configuration the routing table showed a lower metric for teh virtual adapter then for the physical. So I changed the interface metric in the network properties by deselecting automatic metric in the advanced network settings.
osql now uses the physical adapter.
The commands OSQL -L and SQLCMD -L will show you all instances on the network.
If you want to have a list of all instances on the server and doesn't feel like doing scripting or programming, do this:
Start Windows Task Manager
Tick the checkbox "Show processes from all users" or equivalent
Sort the processes by "Image Name"
Locate all sqlsrvr.exe images
The instances should be listed in the "User Name" column as MSSQL$INSTANCE_NAME.
And I went from thinking the poor server was running 63 instances to realizing it was running three (out of which one was behaving like a total bully with the CPU load...)
I just installed Sql server 2008, but i was unable to connect to any database instances.
The commands #G Mastros posted listed no active instances.
So i looked in services and found that the SQL server agent was disabled. I fixed it by setting it to automatic and then starting it.
I had this same issue when I was assessing 100+ servers, I had a script written in C# to browse the service names consist of SQL. When instances installed on the server, SQL Server adds a service for each instance with service name. It may vary for different versions like 2000 to 2008 but for sure there is a service with instance name.
I take the service name and obtain instance name from the service name. Here is the sample code used with WMI Query Result:
if (ServiceData.DisplayName == "MSSQLSERVER" || ServiceData.DisplayName == "SQL Server (MSSQLSERVER)")
{
InstanceData.Name = "DEFAULT";
InstanceData.ConnectionName = CurrentMachine.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("SQL Server (") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("(") + 1,
ServiceData.DisplayName.IndexOf(")") - ServiceData.DisplayName.IndexOf("(") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("MSSQL$") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("$") + 1,
ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf("$") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
Will get the instances of SQL server
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"
or Use
SQLCMD -L
Here is a simple method:
go to
Start then
Programs then
Microsoft SQL Server 2005 then
Configuration Tools then
SQL Server Configuration Manager then
SQL Server 2005 Network Configuration then
Here you can locate all the instance installed onto your machine.
I know its an old post but I found a nice solution with PoweShell where you can find SQL instances installed on local or a remote machine including the version and also be extend get other properties.
$MachineName = ‘.’ # Default local computer Replace . with server name for a remote computer
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’, $MachineName)
$regKey= $reg.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL" )
$values = $regkey.GetValueNames()
$values | ForEach-Object {$value = $_ ; $inst = $regKey.GetValue($value);
$path = "SOFTWARE\\Microsoft\\Microsoft SQL Server\\"+$inst+"\\MSSQLServer\\"+"CurrentVersion";
#write-host $path;
$version = $reg.OpenSubKey($path).GetValue("CurrentVersion");
write-host "Instance" $value;
write-host "Version" $version}
If your within SSMS you might find it easier to use:
SELECT ##Version

Resources