Why Excel VBA can't query tables with the # symbol? - sql

I'm trying to query a table, call it history#integration.
When I query the table, with this type of query:
select * from history#integration where id=5
and get the expected output.
With excel I connect to the database in this way:
cn.Open ( _
"User ID=" & userID & _
";Password=" & password & _
";Data Source=" & datasource & _
";Provider=MSDAORA.1")
but I get a runtime error of data type is not supported. I've verified using the exact same connection I can query the database with other "standard" tables like select * from history. Any thought on how I can get the "correct" type.

In Oracle (assuming this is what you're using, and it would be helpful to state that in your question) # is typically used to represent a database link: likely it's not part of the table name, but the table "history" is actually in a different database linked to by a DB link named "integration".
Not all datatypes are selectable over an Oracle DB link (LOB types for example)

# is a reserved character in SQL. Try surrounding the table name with brackets like: [history#integration].

Related

How to create a live connection between MS Access and SQL Server?

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.

In MS Reporting Services, how do you set a dynamic dataset, based on a selectable Report database parameter

In MS Reporting Services, how do you set a dynamic dataset, based on a selectable Report database parameter?
For example, I have one dataset, Insurers, that has a text SQL Query, instead of a stored procedure, and I need to use the database that is selected by the user in the Report database parameter as the datasource for the Insurers dataset.
Assuming the database is always going to be in the same instance, you can do this more simply by just using an expression string for your query and concatenating the database parameter into the FROM clause of the query.
I was able to figure it out.
In the Data Source Properties, I select Embedded connection. And then in the connection string, I created a dynamic expression.
= "Data Source=" & Parameters!ServerName.Value & ";Initial Catalog=" & Parameters!Database.Value & ";Persist Security Info=True;User ID=userID;Password=password;Connection Timeout=260;"
And then on the Report Server, after deploying the report, I select custom datasource, and put in the username and password for the datasource. The connection string should show the text next to it.

MS Access: Method to process SQL without using RecordSource

I would like to be able to find the last record in a table easily for SQL INSERT INTO table statement. I was hoping there would be a MS Access object or function which could read a SQL statement without requerying the whole context just to find specific counts or records. As I have been programming the only code I know that reads SQL is a recordset, is there a dummy copy or source you could just read without repointing the record to another? Otherwise, I need a way to access the table in VBA and count all records with a method. If this is not code yet is should be, this would make it so easy to get around code dialects, other methods (unless you need to use form objects) if you know SQL.
I have tried several things, such as that cast a tbl variable but there would be a type mismatch.
This needs a last statement so I get the new record... I need to know how to get the last record in the table with a count.
CurrentDb.Execute "INSERT INTO FormsHelpTable ([ID], [HelpTitle], [Comment]) VALUES " & _
"(" & (lastRecTbl + 1) & ", '" & Me.Text53 & "', '" & Me.Comment & "')", dbFailOnError
Me.RecordSource = "SELECT * FROM FormsHelpTable"
Me.Requery
This worked to find the last record:
http://www.minnesotaithub.com/2013/08/count-records-vba-microsoft-access-2010/
Great code too.

Using ADO/DAO Connection to Download data from SQL Server

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.

SQL/ASP - Invalid column name 'Email'

i am having trouble adding stuff into the Email column. I can add stuff into the Username column but for some reason i get the following error:
Microsoft OLE DB Provider for SQL Server error '80040e14'
Invalid column name 'Email'.
When I use this code:
Set rstSimple = cnnSimple.Execute("insert into SALT (Email, Username, FirstName, LastName, ActivationCode, TransactionID, ClientID) VALUES ('" & Request.QueryString("payer_email") & "','" & Request.QueryString("payer_email") & "','" & Request.QueryString("first_name") & "','" & Request.QueryString("last_name") & "','" & Request.QueryString("hash") & "','" & Request.QueryString("txn_id") & "','" & Request.QueryString("client_id") & "')")
Can somebody please help me?
Thank you
If the error states "Invalid column name 'Email' I would check:
Does the column 'Email' exist in the database and in that format?
What value are you inserting into the column? If Username works and Email doesn't, are they different types? Maybe Email doesn't except NULL values and Username does? If you are then trying to put a null e-mail address into Email then it won't work.
Other that looking at your database schema, there isn't much more I can guess from this.
Paul
I just encountered a similar problem today... reading values off the MSSQL database, the "Email" column is coming up blank/null in my ASP program.
But checking the table using SQL Enterprise Manager shows there is data in the "Email" column.
I couldn't find anything wrong with my code and I'm running out of ideas. Just for the heck of it, I tried to rename the field "Email" to something else, like "UserEmail". And voila!!!! My code is working again.
So try renaming your column "Email" to something else. I did some search and couldn't find anything that says "Email" is a reserved word in MSSQL and that you can't use "Email" for column names.
I do not know if it has an email
column in it because none of the damn
programs let me connect to the
database
Try downloading and connecting SqlDbx to your database using the same ODBC connection. It will allow you to view the schema of your database easily and to edit and execute queries.
http://www.sqldbx.com/ (free for personal use)
Microsoft also has a SQL Server management express tool that is also free