At the moment, I have set up an SQL database with one table with various fields.
I have not done VB scripts before and at the moment i have in my script
objConnection.Open _
"Provider=SQLOLEDB;" & _
"Data Source=atl-sql-01;" & _
"Trusted_Connection=Yes;" & _ "InitialCatalog=SCM-69462\SQLEXPRESS;" &
my InitialCatlog= I have entered the server which the database is on. This server has many different databases on already (from different students). I have set up a database X and created a table within this database. A basic table with 4 fields. With the intialCatalog string, will this locate the specific database on the server or do I need some more information? Or would I simple put "InitialCatalog=x" & x being the database name on the server, not the server itself?.
According to THE authority the connection string should look like:
Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=myDataBase;
Integrated Security=SSPI;
so try:
Provider=sqloledb;Data Source=SCM-69462\SQLEXPRESS;Initial Catalog=X;
Integrated Security=SSPI;
Then test, whether adding "Trusted_Connection=Yes" helps.
Related
I have an MSaccess database with 2 tables (process and data_type). Each process can contain 0-many types of data_type. Within access, I have a form that displays a process with a list-box, (see pic), that has all of the data_types. The user can then check the data_types that each process has.
We are in the process of migrating the data from access to MySQL. As part of that I've created a process2data table that links the process and data_type table. Unfortunately, I don't know how to create a form in Access (we are still, for now, using that as our display engine) that accomplishes the same thing with the online data.
You can download what I'm trying to do here:
(For simplicity, I've put copies of the online data tables that are in mySQL as offline tables in Access.)
The multi-valued fields works only on MS-Access databases, to emulate we need to add VBA code and a table to store the values.
Create intermediate table, in this case I have created [ProcessList_DataType], the [checked] field will be used to include the data type, see picture:
Create a form for ProcessList and a subform for [Datatypes] and [ProcessList_DataType] combined tables. Don't forget configure the link master fields.
Add code to check the referenced values are present on intermediate table:
Private Sub Form_Current()
On Error GoTo ErrExit
If Not IsNull(Me!ProcessID) Then
sql = "INSERT INTO ProcessList_DataType(ProcessList,DataType) " & _
"SELECT " & Me!ProcessID & ",datatype_id " & _
"FROM DataTypes WHERE datatype_id not in " & _
"(SELECT datatype_id from FilterQuery " & _
" WHERE ProcessList = " & Me!ProcessID & " )"
Set db = CurrentDb()
db.Execute sql
cnt = db.RecordsAffected
If cnt > 0 Then
NeedRefresh = True
End If
End If
ErrExit:
End Sub
Enjoy!
I have a folder which contain's Sub folders(City Names) and in those sub folders I have excel files. I have to take all the excel files from the sub folder and load them into a SQL Server table basing on the city name. The files are structured as below.
Dallas Folder contain's these files
DALLAS_Cars_2011.xls
DALLAS_Trucks_2011.xls
DALLAS_Bikes_2011.xls
My requirement is I have to load the cars data into cars table and Trucks data into Trucks tables, basing on their names and all the city file's should go into same table like cars's, trucks. And I have to create an ID column basing on the city name it can be based on the alphabetical order
can any of the guys help me in this.
First of all I am using SQL Server Express 2008 (R2) and with this I was able to export MS Excel File into my Database. I know at least three ways to do this:
1) Using Import and Export Data (whether 32 bit or 64 bit).
2) Using SQL per se
3) Programmatically like using C# or VB.net
In Import and Export Data just go to your MS SQL Server under All Programs and from there follow the direction. You specify the Data Source as MS Excel and then you Identify your Destination and make sure you Identity to which Database you want to put it.
In Using SQL you could simply use the following command just change accordingly to your own need.
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=YES;Database=c:\CityName\DALLAS_Cars_2011.xls','select * from [sheet1$]')
However, if you encounter problem like :
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.
Try to add this lines:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=YES;Database=c:\CityName\DALLAS_Cars_2011.xls','select * from [sheet1$]')
Otherwise if you still encounter problem that probably means that your MS Excel is 32 bit and you are running on 64 bit SQL Server. So, you are better off doing the 1st method.
Finally if you know programming in VB.Net or C# then you could probably code it like this:
Dim cn As ADODB.Connection
Dim strSQL As String
Dim lngRecsAff As Long
Set cn = New ADODB.Connection
cn.Open "Provider=SQLOLEDB;Data Source=<server>;" & _
"Initial Catalog=<database>;User ID=<user>;Password=<password>"
'Import by using OPENDATASOURCE.
strSQL = "SELECT * INTO XLImport6 FROM " & _
"OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', " & _
"'Data Source=C:\test\xltest.xls;" & _
"Extended Properties=Excel 8.0')...[Customers$]"
cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
See source here
Or you could also use a library from EPPlus like what I did in one of my program.
See its link here.
You can use SSIS to load the excel files into SQL Server.
Create 3 variables: File, City and Table
Create an expression for the City variable to retrieve the City part from File
Do the same for Table
Create a foreach file enumerator
Assign the fully qualified name to the File variable
Create a data flow task that contains an excel source and ole db destination
Create an excel connection which retrieves uses the File variable
Create an ole db connection, assign it to the ole db destination and choose the Table variable as destination table.
Example of expression for city:
If you're File variable contains: C:\temp\Dallas\Dallas_Trucks_2011.xls
SUBSTRING(#[User::File], FINDSTRING(#[User::File], "\\", 3) + 1, FINDSTRING(SUBSTRING(#[User::File], FINDSTRING(#[User::File], "\\", 3) + 1, 99), "_", 1) -1)
The expression should return Dallas. It retrieves the part betweent he third \ and the first _
The following expression returns Trucks by retrieving the part between the first _ and second _
SUBSTRING(#[User::File], FINDSTRING(#[User::File], "_", 1) + 1, FINDSTRING(SUBSTRING(#[User::File], FINDSTRING(#[User::File], "_", 1) + 1, 99), "_", 1) -1)
You can also add a derived column in the data flow task to add the City as a column.
EDIT: I'm actually not 100% sure this will work with a dynamic Excel file and Table definition.
I'm running a Pivotal application (5.9) and have a server process which always crashes (MS SQL error 1206).
I have a Pivotal "active form" with an update button, which, when clicked, calls a server process (VB 6 custom DLL)
This custom DLL :
retrieves the list of all users who can use the Pivotal application ("users" standard table) by using the Pivotal API, and then creates its own connection to another database using a connection string)
For each users, it constructs and run the a query :
strSql = select SUM(stoResourceSize) totalResourceSize from " & dbName &
".dbo.Resource Where StorageID = 3 and XptDestinationAddress like "
strSql = strSql & "'%" & userName & "%'"
The connection string used to run the query is the following :
strConnect = "Driver={SQL Server};" & _
"Server=" & SatteliteName & ";" & _
"UID=" & SyncStreamDBName & ";" & _
"Trusted_Connection=Yes"
It works fine but the query crashes after about 80 users processed, with error 1206 and SQLState = 37000
I can reproduce that problem every single time. At a given time, this query will crash.
I have added a lot of trace and the last query works fine if I run it on the server "by hand".
It doesn't crash on the same user every time, it looks like it is random. Besides, in the application there exists another server procedure which can run the same query but only for one user. That one will run fine and never crash.
I have also tried to enabled ODBC trace but it wouldn't give me any useful information.
I'm pretty confidnet it is a connection or configuration problem but I don't know what.
This problem is reproducible both in developpment and testing environnments.
edit: actually it seems that my server process can crash at various points, not necessarily when executing that request.
It seems to crash when I open ADODB recordsets (of course, before touching any recordset, I verify that both EOF and BOF are false, and they are).
I have my database split into a backend containing the data tables and a frontend containing forms, queries, reports, and modules, with the tables linked. One of the tables gets its data from an excel sheet; normally I'd use a linked table but if any queries are open then the excel sheet cannot be opened, so instead I use a saved import to pull all the data from the excel sheet into the table.
Now, I'd like to add a button to the menu on my frontend that runs DoCmd.RunSavedImportExport "savedimportnamehere" except the saved import is on the backend, so I'd have to send that command to the backend... and I'm not quite sure how to do that. If anyone could point me in the right direction I'd appreciate it.
You can run a command against an instance of MS Access, so:
Dim apAccess As New Access.Application
apAccess.OpenCurrentDatabase ("c:\docs\backend.mdb")
apAccess.DoCmd.RunSavedImportExport "savedimportnamehere"
You can also run a query against an instance of the db or a connection:
sSQL="INSERT INTO Table1 ( ADate ) " _
& "SELECT SomeDate " _
& "FROM [Excel 8.0;HDR=YES;DATABASE=Z:\Docs\Test.xls].[Sheet1$a1:a4]"
I manage an SQL Server 2005 Database and I would like to give read-only access to the necessary tables to a group of 20-30 networked users who are able to use the GUI in MS Access 2007 to write or modify their own queries to the database, with some help.
I would like to distribute an Access database with a single form that would create links to the necessary tables. All of these users are included in a group with read-only permissions to the SQL Server database. I can distribute a dsn file for the connection, but I haven't found a way to programatically create the links to the 50 or so tables they might need, with their network credentials from an otherwise empty Access database.
I found a line of VB code from answer to a similar question onstackoverflow (below), but I was wondering if there was any simpler way than running the modified command once for each of the 50 or so tables.
DoCmd.TransferDatabase acLink, "ODBC Database", "ODBC;DRIVER=Microsoft ODBC for Oracle;SERVER=myserver;UID=myuser;PWD=mypassword", acTable, "SCHEMA.TABLE", "TABLE", False, True
I just wrote an article last week detailing a way to quickly link all tables in an SQL Database to Access. Here are some Access methods that will help. Read the article for more instructions on using it.
You will need to reference the Microsoft ActiveX Data Objects library.
Sub LinkAllTables(Server As String, database As String, OverwriteIfExists As Boolean)
'Usage Example (link all tables in database "SQLDB" on SQL Server Instance SQO01, overwriting any existing linked tables.
'linkalltables "SQL01","SQLDB", true
'This will also update the link if the underlying table definition has been modified.
Dim rsTableList As New ADODB.Recordset
Dim sqlTableList As String
sqlTableList = "SELECT [name] as tablename FROM sysObjects WHERE (type = 'U')"
rsTableList.Open sqlTableList, BuildSQLConnectionString(Server, database)
While Not rsTableList.EOF
If LinkTable(rsTableList("tableName"), Server, database, rsTableList("tableName"), OverwriteIfExists) Then
Debug.Print "Linked: " & rsTableList("tableName")
End If
rsTableList.MoveNext
Wend
rsTableList.Close
Debug.Print "Done."
End Sub
Function LinkTable(LinkedTableAlias As String, Server As String, database As String, SourceTableName As String, OverwriteIfExists As Boolean)
'This method will also update the link if the underlying table definition has been modified.
'The overwrite parameter will cause it to re-map/refresh the link for LinktedTable Alias, but only if it was already a linked table.
' it will not overwrite an existing query or local table with the name specified in LinkedTableAlias.
'Links to a SQL Server table without the need to set up a DSN in the ODBC Console.
Dim dbsCurrent As database
Dim tdfLinked As TableDef
' Open a database to which a linked table can be appended.
Set dbsCurrent = CurrentDb()
'Check for and deal with the scenario ofthe table alias already existing
If TableNameInUse(LinkedTableAlias) Then
If (Not OverwriteIfExists) Then
Debug.Print "Can't use name '" + LinkedTableAlias + "' because it would overwrite existing table."
Exit Function
End If
'delete existing table, but only if it is a linked table
If IsLinkedTable(LinkedTableAlias) Then
dbsCurrent.TableDefs.Delete LinkedTableAlias
dbsCurrent.TableDefs.Refresh
Else
Debug.Print "Can't use name '" + LinkedTableAlias + "' because it would overwrite an existing query or local table."
Exit Function
End If
End If
'Create a linked table
Set tdfLinked = dbsCurrent.CreateTableDef(LinkedTableAlias)
tdfLinked.SourceTableName = SourceTableName
tdfLinked.Connect = "ODBC;DRIVER={SQL Server};SERVER=" & Server & ";DATABASE=" & database & ";TRUSTED_CONNECTION=yes;"
On Error Resume Next
dbsCurrent.TableDefs.Append tdfLinked
If (Err.Number = 3626) Then 'too many indexes on source table for Access
Err.Clear
On Error GoTo 0
If LinkTable(LinkedTableAlias, Server, database, "vw" & SourceTableName, OverwriteIfExists) Then
Debug.Print "Can't link directly to table '" + SourceTableName + "' because it contains too many indexes for Access to handle. Linked to view '" & "vw" & SourceTableName & "' instead."
LinkTable = True
Else
Debug.Print "Can't link table '" + SourceTableName + "' because it contains too many indexes for Access to handle. Create a view named '" & "vw" & SourceTableName & "' that selects all rows/columns from '" & SourceTableName & "' and try again to circumvent this."
LinkTable = False
End If
Exit Function
End If
On Error GoTo 0
tdfLinked.RefreshLink
LinkTable = True
End Function
Function BuildSQLConnectionString(Server As String, DBName As String) As String
BuildSQLConnectionString = "Driver={SQL Server};Server=" & Server & ";Database=" & DBName & ";TRUSTED_CONNECTION=yes;"
End Function
Function TableNameInUse(TableName As String) As Boolean
'check for local tables, linked tables and queries (they all share the same namespace)
TableNameInUse = DCount("*", "MSYSObjects", "(Type = 4 or type=1 or type=5) AND [Name]='" & TableName & "'") > 0
End Function
Function IsLinkedTable(TableName As String) As Boolean
IsLinkedTable = DCount("*", "MSYSObjects", "(Type = 4) AND [Name]='" & TableName & "'") > 0
End Function
In addition to what David proposed, you could have a local (client side) table listing the list of tables available through the SQL connection. You could then write a piece of VBA code that will browse this table to establish all corresponding connections:
Dim rsTable as DAO.recordset
set rsTable = currentDb.openRecordset("Tbl_Tables")
if rsTable.EOF and rsTable.BOF then
else
rsTable.moveFirst
Do while not rsTable.EOF
DoCmd.openDatabase .... 'enumerate here all needed paarmeters with rsTable.fields("tableName") in the string'
rsTable.moveNext
Loop
Endif
rsTable.close
set rsTable = Nothing
This piece of code was written on the fly, so I cannot garantee it will work 'as is'. This code could for example be launched at startup (through the autoexec macro) so that your users will have their links ready when they open their app.
The 'view-only' thing can be easily managed by listing corresponding users (or, if you have a Domain, the corresponding group of users) as 'data readers' on your SQL server.
Is there a special reason why you want to re-create the links every time?
It would be much simpler to create once the mdb with the linked tables, and distribute that mdb to your users.
You might also want to link SQL Server Views (instead of tables) to Access tables, in order to make sure it's read only, maybe pre-join some tables, and eliminate some fields they do not require.
Why not use an Active Data Project in Access?
Linked tables are really only useful if you also need local (unlinked) tables. If you can keep all the tables and views on SQL Server and leave the forms in Access, an ADP will work fine and won't require "linking" any tables manually or via scripting.
In response to Patrick below, if you don't want them mucking around creating queries in your real SQL Server store, create a second SQL Server database that they have rights to create and update queries in, and create VIEWs like the following:
CREATE VIEW mytable AS SELECT * FROM [real database].dbo.mytable
Thus, when you change your master data tables, you only have to make a change to the VIEW in their shared SQL Server database, not a change to each Access database.
Side advantage #1: the users can see each other's queries, thus giving a social aspect of easily sharing good queries.
Side advantage #2: since they are all in one place, you can use SQL Server to detect which user queries will break if you make a change to one of the read-only tables (by searching the view definitions created by Access).
If your SQL Server uses Windows security instead of SQL Server security, then you don't have to supply a username/password in your connect string.
Here's the standard way to do this:
on your development machine, create a DSN for your SQL Server database.
use FILE | GET EXTERNAL DATA | LINK TABLES to link to the tables via ODBC.
get Doug Steele's code to convert to DSN-less connect strings.
then just distribute the front end as is to your users.
The key to this scenario is using Windows security rather than SQL Server security -- Access silently passes the credentials when it requests the connection via ODBC. This is one reason I'd never use SQL Server security -- too much trouble!