The data I am using is stored in a SQL database and an Access database. Regular data entry needs to be made in the Access database, however, I would like to write my queries in SQL Management Studio. I have connected the two databases using an ODBC connection and I can now view the tables in Management studio but the connection is not live, so any updates in Access are not reflected in the tables in Management Studio.
You can create a linked table from Access to SQL Server (INSERT INTO). You can use SQL or VBA to export all data from Access to SQL Server.
Here is one idea.
Sub modExportToPG()
Dim rs As DAO.Recordset
'We only want to export physical user defined visible and hidden tables
Set rs = CurrentDb.OpenRecordset("SELECT Name " & _
" FROM MSysObjects " & _
" WHERE Type=1 AND Flags < 9 ORDER BY Name;")
Do Until rs.EOF
'export the tables but export as lower case table names
DoCmd.TransferDatabase acExport, "ODBC Database" _
, "ODBC;DRIVER={PostgreSQL Unicode};DATABASE=mydb;SERVER=myserver;PORT=5432;UID=myuser;PWD=mypwd" _
, acTable, rs("Name"), LCase(rs("Name"))
rs.MoveNext
Loop
rs.Close
End Sub
Also, see this for more ideas.
https://www.mssqltips.com/sqlservertip/1480/configure-microsoft-access-linked-tables-with-a-sql-server-database/
Came upon this s little late but I am in the midst of working through a project where we update SQL side tables at the same time that we update local and shared (server side) Access tables. It is a fairly extensive application, but the SQL updates are relatively easy and there are options. The application integrates with a Point of Sale back office server and we are sensitive to the data that gets updated instantly, so those items get tucked into batches that require approval before they get "posted" to SQL. Those items that are not sensitive we post immediately using the afterupdate property for each field on the main form using the following code (sample only):
Private Sub Field.AfterUpdate
Dim Var1 as string
Dim Var2 as string
Dim Var3 as string
'Capture Before and after values for the field (as well as using the_
newvalue to post to SQL, we store these separately as audit records_
so we capture both old and new).
Var1 = Me.Field.OldValue
Var2 = Me.Field.NewValue
Var3 = Me.PID.Text
'Execute the SQL update
DoCmd.DbExecute "Update dbo.SQLTABLE SET SQLField = '" & Var2 & "'_
WHERE SQLTABLE.PID = '" & Var3 & "'
End Sub
Note: PID is a record id attached to every record in the access form that matches a corresponding record in a SQL Table (primary key).
It is a lot of work if you have a number of fields to post but it's as good as it gets using linked tables in my experience. This is a simple example and ours are far more extensive, but it does the trick.
Related
Problem:
I'm trying to import a portion of a table from a remote informix db into an access 2016 database. The table to be partially imported contains account information and is > 2 GB (which as I understand it is the max size of a access db).
I only need information for the last year which is much less than 2 GB but the information must be updated at the end of each day.
Two solutions I have seen online are:
(A) Link the tables:
I'm reluctant to do this for two reasons:
1) I don't want additional load placed on the server everytime the enduser of the access db runs a report.
2) I don't want any changes carried out in the access DB to carry over to the live informix DB (this is absolutely cruical)
(B) Copy over the entire table via the access GUI
I don't think this is a viable solution for the following reasons:
1) The table is over 2GB
2) Reports must be ran on the table everyday with daily updated information. This would require pulling the entire informix table into access everyday.
Work So far:
I have succefully connected to the informix db from access via creating a dsn for the informix db.
I have also sucessfully imported a smaller table from the informix server via VBA with the following code:
DoCmd.TransferDatabase acImport, "ODBC Database", "ODBC;DSN=My_DSN_Name;UID=odbc;PWD=My_PWD;LANGUAGE=us_english;" & "DATABASE = My_DB_Name", acTable, "My_Destination_Tbl_Name", "TestTableImport", False, True
My ideal solution would see the enduser of the access db press a button that updates the local access copy of the db with all changes made to the informix db since the last update.
I have limited experience with access and VBA so would really appreciate any pointers on how I should proceed. Perhaps I have overlooked something simple?
Thanks for reading and any advice you can provide,
John
Ummmm.... assuming the data in the table is static (no updates to column data, just new rows) you could do something like importing whatever subset of data you want in Access and then every time you click a button run a macro to check what is the latest row in the access table.
Use that info to select only new rows from the ODBC source and insert them in the access table.
I tried this with Access 2013:
Sub test()
Dim cnDB As New ADODB.Connection
Dim rsRecords As New ADODB.Recordset
' find last row
Set db = CurrentDb
strSQL = "SELECT TOP 1 empno As lastemp FROM informix_employee ORDER BY empno DESC"
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
lastemp = rs("lastemp")
rs.Close
' get new rows from odbc source
DoCmd.SetWarnings False
cnDB.Open "DSN=ids1210;uid=informix;pwd=password"
rsRecords.Open "Select * from employee where empno>" & lastemp, cnDB
Do While Not rsRecords.EOF
strNaam = rsRecords.Fields(0).Value
rsRecords.MoveNext
' update access table
DoCmd.RunSQL ("insert into informix_employee (empno) values ('" + strNaam + "')")
Loop
rsRecords.Close
Set rsRecords = Nothing
cnDB.Close
Set cnDB = Nothing
db.Close
End Sub
It's a basic example, but should give you an idea of how to do it.
The code above inserts only one column per row (empno), you will need go through your table and do the insert with all the columns (basically create the insert ............. statement for your table)
'informix_employee' is the Access table.
'employee' is the Informix table.
Also, you need to reference ADO, e.g. 'Microsoft ActiveX Data Objects 6.1' to get it working, otherwise it will fail as the ADODB object wont be there.
If the Informix table does get some column updates (not just new rows) it would be quite difficult, as nothing (IDS/ODBC/Access) will be able to tell you which rows were updated without getting the data and comparing it with the previous set.
So I have a server and an access database. I would like to look at specific information from a table on the server, but this table has billions of records (too big for access).
Would it be possible to create a form where a user clicks on a specific name on that form and it runs a pass through query to the server to pull just those specific names? So if I click on the name "Tom" it runs a pass through query to the server and returns all records in the "name" column equal to "Tom".
What kind of server? MSSQL? MySQL? Oracle?
With same VBA code it is not that difficult to get results from a MSSQL server (don't know about other DBs). Add a button to your form and add a onClick-event.
Private Sub btnTEST_Click()
Dim cnn As New ADODB.Connection
Call cnn.Open("YOUR_CONNECTION_STRING")
Dim rs As ADODB.Recordset
Set rs = cnn.Execute("SELECT Field1 FROM BigTable WHERE Field2 = Forms!YourForm!lstboxField")
While Not rs.EOF
Debug.Print rs("Field1")
rs.MoveNext
Wend
rs.Close
End Sub
I am trying to figure out how to download using an ADO/DAO connection in Access VBA to get the contents of a table from SQL server. I am trying to avoid using a linked table because the DB requires a password and I keep running into issues with getting it to not ask for the login info. Are there any ideas or references for me to start with on this matter?
It appears either way you'll need to provide SQL credentials.
There's more involved without linking a table, basically you'd want a recordset for the source and the "target" table to iterate over.
targetrs = CurrentDb.OpenRecordset("Target", dbOpenTable)
Dim Con As New ADODB.Connection
Dim sqlStr As String
Con.Open _
"Provider = sqloledb;" & _
"Data Source=SqlServer;" & _
"Initial Catalog=MyDB;" & _
"User ID=sa;" & _
"Password=p#ssW0rd;"
Dim rsSource As New ADODB.Recordset
rsSource.Open "select * from SOURCE", Con
do until rsSource.eof
targetrs.addnew
for each field in rsSource
targetrs.fields(field.Name) = rsSource.fields(field.Name)
next
targetrs.update
rssource.movenext
loop
Since you still have to have the credentials, you could dynamically link the table instead:
docmd.TransferDatabase acLink,"ODBC Database",
"ODBC;Driver={SQL Server};Server=MySQLServer;Database=MYSQLDB;
Uid=USER;Pwd=PASSWORD",acTable,"SQLtable","MyAccessTable"
Use of a linked table does not require you store or have the user password in that linked table.
If you execute a SINGLE logon at application startup then all linked tables will work.
Linked tables work WITHOUT a prompt for user or password.
Linked tables work WITHOUT you having to store the user ID or password in the link.
Access will cache the user name + password if you logon as per the instructions here:
http://blogs.office.com/b/microsoft-access/archive/2011/04/08/power-tip-improve-the-security-of-database-connections.aspx
So to download a table to a local, then you ONLY need this code:
For a new local table (create table query):
CurrentDb.Execute "SELECT * INTO LocalTableCreate FROM ServerTable"
Append to existing table:
CurrentDb.Execute "INSERT INTO LocalTable SELECT * FROM ServerTable"
And if some really strange reason and desire exists create and promote world poverty and do things the hard way like a turtle with time to waste and not use a linked table?
Well you could create a linked table via the “transfer database” command. It is only one extra line of code in front of the above code and then AGAIN the above two examples would work fine.
However I see little if any advantage to creating + deleting a linked table.
I suppose for reasons of performance or perhaps for security or the legitimate reason of you not knowing the table ahead of time? Then I would suggest you use a saved a pass-though query as performance will be even faster.
So you can use this code:
Dim qdfPass As DAO.QueryDef
Set qdfPass = CurrentDb.QueryDefs("MyPass")
qdfPass.SQL = "select * from dbo.MyTable;"
CurrentDb.Execute "INSERT INTO LocalTable SELECT * FROM MyPass”
Note that the sql used in above qerydef MUST be native T-SQL and can be a view or even a store procedure like:
qdfPass.SQL = "exec sp_myCoolStoreProc;"
And the stored procedure can even be passed a parameter like this:
qdfPass.SQL = "exec sp_myCoolStoreProc " & strMyParam
and then :
CurrentDb.Execute "INSERT INTO LocalTable SELECT * FROM MyPass”
So we can even use a select into/append from a store procedure by doing the above and the table/sql server side is dynamic or can even be a stored procedure. Again VERY little code.
I would suggest you avoid the idea proposed here to write recordset looping code unless one really has the desire to write looping code when none is required. And things like PK would have to be dealt with separate in code if you use such loops since the local pk column may need to be skipped (you simply leave that column out of the select SQL).
Note again that the connection string saved for the pass-though query does NOT require the user ID and password by using the above link showing how to “logon” to SQL Server. And if the table is known, then again a saved table link or pass-though query will suffice here.
I am a relative newbie and trying to insert multiple rows (and data from textboxes) from one table into another and am stuck.
This SQL identifies the data to be inserted into the table
strsql = "SELECT '" & textbox1.text & "', '" & Textbox2.text & "', "
strsql = strsql & " a.TaskNum, a.StartDay, a.NumofDays FROM VETTimeLines as a"
strsql = strsql & " ORDER BY a.StartDay"
I started out along the lines of -> Insert into StudentProgram Values() code shown above, after 3 days of trying I now look forward to your advice.
Many thanks in anticipation
Peter
Inserting data using C# can be performed in variety of ways such as using Entity Framework or using ADO.NET, as you have chosen to do in this case.
Using ADO.NET you either write the insert as you did or by using DataAdapter approach. DataAdapter is capable of creating the SQL code for you, amongst other things. For example see:SQL DataAdapter. It is a good idea to not build a SQL string as you did because of sql injection threat as #Joel Coehoorn indicates in his comment above.
One way to overcome this is by using Parameters as shown in the above link. If you decide to provide the SQL for insert yourself with parameters, here is a good example:StackOverFlow-Insert using ADO.
The idea behind all of the above code is to create a connection object, create a parameter object, create a command object, open the database connection, execute the command and close the connection.
Try one of the above approaches and let's know your specific issue if any arises.
Scenario
I have a database made up of 4 columns and 6 million rows.
I want to be able to be able to use Excel to query this data in the same way in which I can query it using the Sql Server Management Studio.
I've had a google around and read a few articles but in all honesty I dont really know enough about the implementation to really know what to look for in a tutorial.
Question
Could someone please explain to me the way in which this works and how I might go about implementing what seems like a fairly simple idea?
EDIT:
So for example -
I have a few simple queries that I want to run on this data.
How do I go about setting these up?
Is the idea that all of the data is first loaded into the excel sheet (or at least linked to the excel sheet so that the user can select the data to view on the fly?) - I cannot physically load in 6 million rows as Excel cannot take that level of data.....
Definitely don't pull all the data into Excel, that will bring it to its knees.
Normally, when I need an Excel (VBA) workbook to retrieve some data from a database, I will just have Excel connect to the database with the appropriate connection string, pass the SQL query string to the database, and retrieve the returned records. Below is some sample VBA code that retrieves some information from an MS Access database.
txtQueryString = "SELECT * "
& "FROM myDataTable " _
& "WHERE fld1 = '" & myCriteria & "'"
txtConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & dbPathString & ";" _
& "Persist Security Info=False"
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
rst.Open txtQueryString, txtConnectString, adOpenKeyset, adLockReadOnly, adCmdText
myData1 = rst.Fields("fld1").Value
myData2 = rst.Fields("fld2").Value
.
.
.
rst.Close
Set rst = Nothing
The connection string to SQL Server will be different. I use this website for all my connection string needs.