I need to get the folder with full path of my SQL Server instance installed on my machine, using vb code.
For example, I have installed instance MyComputer\MyInstanceName.
I know it is in C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL
but how can I get this path using vb.net code?
Thanks
It's not all that obvious, but you can find everything you're looking for in the registry.
Basically:
you need to inspect the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL subkey to find the installed instances and their "internal" names
with that internal name, you can inspect the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(internal name)\Setup node to find everything you might want to know about that instance
In C# code (and for a 64-bit OS, with 64-bit versions of SQL Server), this would be:
// open the 64-bit view of the registry, if you're using a 64-bit OS
RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
// find the installed SQL Server instance names
RegistryKey key = baseKey.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");
// loop over those instances
foreach (string sqlInstance in key.GetValueNames())
{
Console.WriteLine("SQL Server instance: {0}", sqlInstance);
// find the SQL Server internal name for the instance
string internalName = key.GetValue(sqlInstance).ToString();
Console.WriteLine("\tInternal instance name: {0}", internalName);
// using that internal name - find the "Setup" node in the registry
string instanceSetupNode = string.Format(#"SOFTWARE\Microsoft\Microsoft SQL Server\{0}\Setup", internalName);
RegistryKey setupKey = baseKey.OpenSubKey(instanceSetupNode, false);
if (setupKey != null)
{
// in the "Setup" node, you have several interesting items, like
// * edition and version of that instance
// * base path for the instance itself, and for the data for that instance
string edition = setupKey.GetValue("Edition").ToString();
string pathToInstance = setupKey.GetValue("SQLBinRoot").ToString();
string version = setupKey.GetValue("Version").ToString();
Console.WriteLine("\tEdition : {0}", edition);
Console.WriteLine("\tVersion : {0}", version);
Console.WriteLine("\tPath to instance: {0}", pathToInstance);
}
}
Related
I want to copy a database to a sql server to another, but i just want to copy structure (views, stored procedures, tables, fields, indexes, etc), no rows.
I tried to generate a script from sql server management but the script is very verbose (task menu > create as)
Follow Below steps for generate script :
Right Click on Database
Select task
Select Generate Script from Task
Follow the steps
Finally finish for complete this process
You can either use the SQL Server Management Object API (see task "creating, altering and removing databases"):
C# Code for generate sql script :
public string GenerateScript()
{
var sb = new StringBuilder();
var srv= new Server(#"Your Database Server Name");
var db= server.Databases["Your Database name"];
var scrpt = new Scripter(srv);
scrpt.Options.ScriptDrops = false;
var obj= new Urn[1];
foreach (Table tbl in db.Tables)
{
obj[0] = tbl.Urn;
if (tbl.IsSystemObject == false)
{
StringCollection sc = scripter.Script(obj);
foreach (var st in sc)
{
sb.Append(st);
}
}
}
return sb.ToString();
}
You case use Copy database wizard
Some limitations of the it are :
1.The Copy Database Wizard is not available in the Express edition.
1.The Copy Database Wizard cannot be used to copy or move databases that:
Are System.
Are marked for replication.
Are marked Inaccessible, Loading, Offline, Recovering, Suspect, or in Emergency Mode.
Have data or log files stored in Microsoft Azure storage.
I am working off of a server housing various SQL databases (accessed via Microsoft SQL Server Management Studio) and am going to use R to perform analyses and explore a specific database within the server. I have network security that permits communication between machines, drivers installed on the R server, and RODBC installed.
When I attempt to establish a Windows ODBC connection in the Control panel>Administrative>Data Sources, I can only add a data source for the entirety of the SQL server, not just for the specifc database I want to look at. I pasted the code I have been experimenting with below.
library(RODBC)
channel <- odbcConnect("Example", uid="xxx", pwd=****");
sqlTables(channel)
sqlTables(ch, tableType = "TABLE")
res <- sqlFetch(ch, "samp.le", max = 15) #not recognizing as a table
library(RODBC)
ch <- odbcDriverConnect('driver={"SQL Server"}; server=Example; database=dbasesample; uid="xxxx", pwd = "****"')
Response: Warning messages:
1: In odbcDriverConnect("driver={\"SQL Server\"}; server=sample; database=dbasesample; uid=\"xxxx", pwd = \"xxxx\"") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect("driver={\"SQL Server\"}; server=sample; database=dbasesample; uid=\"xxxx\", pwd = \"xxxx!\"") :
ODBC connection failed
Any insight into this issue would be much appreciated.
Although while querying with the sqlQuery() function you can specify database, schema and table, e.g.
library(RODBC)
con = odbcConnect(dsn = 'local')
sample_query = sqlQuery(con,'select * from db.dbo.table')
I have not found a way to define the database from within the function parameters while using sqlFetch() or sqlSave(). An indirect way would be to define the default database in the dsn (as written in the comments). But then, you would need a different dsn for each database you would like to use.
A better solution would be to use the odbc and DBI packages instead of RODBC, and define the database in the connection statement e.g.
library(dplyr)
library(DBI)
library(odbc)
con <- dbConnect(dsn = 'local',database = 'db')
copy_to(con, rr2, temporary = F)
By the way, I found copy_to to be much faster than the equivalent sqlSave of RODBC.
In "Talend Data Integration" I want to create a connection using JDBC to a Progress OpenEdge database. I have no experience whatsoever with this type of connection.
My ODBC-connections to the same resources work fine, but Talend requires a JDBC connection to function properly.
The connection settings in Talend I have at the moment are:
DB Type: General JDBC
JDBC URL: jdbc:sqlserver://db-name:port;databaseName=**
Driver jar: ??? (which jar-file do I need for OpenEdge?)
Class name: ??? (which class name do I need for OpenEdge?)
User name: *
Password: *
Schema: ??? (don't know what this means...?)
Mapping file: ??? (which xml-file do I need for Progress OpenEdge?)
EDIT: I am using Windows 7 on a 64-bit machine, using Talend Open Studio for Data Integration version 5.3.0.r101800.
Setup OpenEdge OBDC connection:
new OdbcConnection("Driver={Progress OpenEdge 10.2B Driver}; HOST=" + host + "; PORT=" + portNumber + "; DB=" + databaseName + "; DefaultIsolationLevel=READ COMMITTED; UID=" + user + "; PWD=" + pasword + ";");
ODBC driver is not included in OpenEdge. The driver must be downloaded and installed!
Setup OpenEdge JDBC connection:
String connectionString = "jdbc:datadirect:openedge://localhost:" + portNumber + ";databaseName=" + databaseName + ";user=" + user + ";password=" + pasword + "";
String cname = "com.ddtek.jdbc.openedge.OpenEdgeDriver";
Class.forName(cname);
connection = DriverManager.getConnection(connectionString);
Include driver in classpath from: C:\Progress\OpenEdge\java\openedge.jar
Setup in http://localhost:9090/fathom.htm: SQL Configuration Java classpath to: #{startup\dlc}\java\openedge.jar;#{startup\dlc}\java\util.jar
More information:
Try 'system' or 'sysprogress' for user;
Try 'SYSTEM' or 'PUB' for
catalog or schema;
Some tools will ask you for an external catalog name that you wanth to use, not from progress.
I found the solution:
What you need are a set of jar-files that are provided with your specific installation of Progress OpenEdge. These files, which are located in a folder called "java", are not commonly available on the internet and they should meet the exact version that you are using. If necessary, you need to contact your database provider. Use these files (you may not find all of them depending on your version of Progress OpenEdge):
progress.jar
openedge.jar
util.jar
base.jar
pool.jar
spy.jar
My url was wrong (it was still set to mySql). Instead use:
jdbc:datadirect:openedge://your-server-name:your-port;databaseName=your-db-name
As class name, use:
com.ddtek.jdbc.openedge.OpenEdgeDriver
I left schema and mapping file blank, and that worked. Good luck!
In my app the users gets to pick from a list of SQL Server in the network. The thing is I need to know if the chosen instance is a local or remote computer.
Is there a way I can ask that SQL instance what computer is she on? Is there a way a can figure that out?
Edit1: I want to know the host name where the SQL Server is hosted so I can then compare that to System.Environment.MachineName and know for sure is that Sql Server is running on the same machine where my app is running
Edit2: ##servername returned my computername\sqlinstance while SELECT SERVERPROPERTY('MachineName') returns just the computername, which is exactly what I want
Use ##Servername, for example:
SELECT ##servername
Alternately you could do this
SELECT SERVERPROPERTY('MachineName')
From MSDN on the differences between these approaches:
The ServerName property of the
SERVERPROPERTY function and
##SERVERNAME return similar
information. The ServerName property
provides the Windows server and
instance name that together make up
the unique server instance.
##SERVERNAME provides the currently
configured local server name.
The ServerName property and
##SERVERNAME return the same
information if the default server name
at the time of installation has not
been changed.
If the local server name has been
changed from the default server name
at installation time, ##SERVERNAME
returns the new name.
Do you actually have login permissions on all the instance(s) of SQL Server? If so you could execute sp_helpserver or ##servername and compare the name returned with Environment.MachineName.
If you don't have login access, you can write a small C# console program to return the server name of every SQL Server instance on the local network:
using System;
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.
// The first column is the server name.
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("============================");
}
}
}
sp_who2 returns the hostname
I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx