Setting NO COUNT ON in VBA ADODB - sql

After hours of frustration I have realized that I have become a victim of Error Messaging Referencing #Temp Table with ADO-SQLOLEDB
When you try to create a ADO recordset based on a #Temp table created
within a stored procedure called by ADO using the SQLOLEDB provider,
you may encounter one of the following error messages...
The solution is to add SET NOCOUNT ON to either the Stored Procedures, or to the VBA code when the recordset is open. At the moment I am stuck with adding it to my VBA code.
The example code that MS gives as a solution is something like:
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandText = "spThatHasTempTable"
cmd.CommandType = adCmdStoredProc
..
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = conn
.Open "SET NOCOUNT ON"
End With
rs.Open cmd, , , , adCmdStoredProc
This works for me. However I feel like that setting SET NOCOUNT ON really should be a part of the Command object construction, but I can't seem to figure out how to do just that.
So how would I include SET NOCOUNT ON when constructing the Command object?

Can you combine the SQL? so your command becomes "set nocount on; select * from table"?
I know in some situations you can't have multiple commands.

Related

Excel VBA to Execute Stored UNION Query from MS Access 2003

I'm writing a function in Excel VBA to execute a stored queries on a database created using MS Access 2003. The code works when the stored query is a simple query, but NOT if the query is a UNION. For example, I'm using the following code to execute the stored queries:
Public Function QueryDB()
Dim cn As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb"
' Open the db connection
cn.Open strConnection
' Create call to stored procedure on access DB
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "testQuery"
cmd.ActiveConnection = cn
' Execute stored query
Dim rs As ADODB.Recordset
Set rs = cmd.Execute()
MsgBox rs.Fields(0) ' prints as expected
QueryDB2 = rs.Fields(0)
' close connections
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Function
If testQuery is a simple query (e.g., does not use UNION), then data is returned as expected. However, if the testQuery contains a UNION, then the Excel VBA code fails (and no particular error is returned). How can I work-around this issue? I'd like to avoid writing the SQL statement in VBA.
Consider using ADO's Open Recordset method. Usually, Execute are for action commands (append/update/delete, stored procedures, etc.). Additionally, if Execute returns a recordset it is only a forward-only (i.e, snapshot with no cursor), read-only recordset without the facilities of MoveNext, RecordCount, Update.
Dim cn As Object
Dim rst As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb"
' Open the db connection
cn.Open strConnection
' Open the recordset
rst.Open "testQuery", cn
Sheets(1).Range("A2").CopyFromRecordset rst
' Close recordset and db connection
rst.Close
cn.Close
Are you still struggling with this? Try using an ODBC Query. Follow the steps listed here.
http://translate.google.pl/translate?js=n&prev=_t&hl=pl&ie=UTF-8&layout=2&eotf=1&sl=pl&tl=en&u=http%3A%2F%2Fafin.net%2FKsiazkaSQLwExcelu%2FGraficznyEdytorZapytanSqlNaPrzykladzieMsQuery.htm
Make sure you have no nulls in your Union and if you do, you must use the NZ Function to convert nulls into zeros.

Change language for ADODB.Recordset or ADODB.Connection

When I retrieve data with a recordset from a connection I cannot control Date Language. This is how I retrieve Data:
Set rsData = New ADODB.Recordset
Set rsData = conODBC.Execute(sql)
The SQL statement has the below line:
TO_CHAR(TO_DATE(TO_CHAR(DB_MONTH), 'MM'),'MON')||DB_YEAR AS DATE_STR
it converts DB_MONTH and DB_YEAR to something like DEC16 and works perfectly fine with SQL Developer.
However if it comes as Recordset Field with VBA the Date is converted to German (I'm working with a German Excel) and I receive DEZ16.
This becomes a problem when I unload the Data into the sheet and continue to work with it since I have no control of how my data string comes back.
You have to set your data language to desired value before you run your query. Should be something like this:
Dim cmd As New ADODB.Command
cmd.CommandType = CommandType.Text
cmd.CommandText = "ALTER SESSION SET NLS_DATE_LANGUAGE = 'AMERICAN';"
cmd.Execute

Execute Query from Access via Excel Query in VBA

Access has saved a query that was designed with the query builder called 'myQuery'. The database is connected to the system via ODBC connection. Macros are all enabled.
Excel Has makes a ADODB connection to connect to the database via
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "MyDatabase.accdb"
End With
Usually you would go ahead and just write your SQL, which is perfectly fine and then just do something like
Dim sqlQuery As String
sqlQuery = "SELECT * FROM myTable"
Set rs = New ADODB.Recordset
rs.Open sqlQuery, con, ...
But I want to access the query that I saved in the access database. So how do I call the saved query in the database that I just connected.
Tried already
con.Execute("EXEC myQuery") but that one told me it could not be find myQuery.
rs.Open "myQuery", con but that one is invalid and wants SELECT/etc statements from it
I think you can treat it like a stored procedure.
If we start right before Dim sqlQuery As String
Dim cmd as new ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "myQuery"
cmd.ActiveConnection = con
Set rs = cmd.Execute()
Then pickup your recordset work after this.
You were nearly there:
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "z:\docs\MyDatabase.accdb"
End With
con.Execute "MyQuery"
Just leave out Exec.
You can add parameters, too, this is a little old, but should help: update 2 fields in Access database with Excel data and probably a Macro
I was able to run an update query that was already saved in Access using:
Connection.Execute "My_Update_Query_Already_Saved_In_Access", adExecuteNoRecords, adCmdStoredProc
This gave me errors until I replaced spaces in the query name with underscores in both the Access database and the execute statement.
This is sort of a hack job, but you can query a query. That is, replace your sql string with the following:
sqlQuery = "SELECT * FROM QueryName;"
Before running this, one must ensure that the Access Database has been saved ie. press Ctrl+S (it is not sufficient that the query was run in Access).
Long time since this thread was created. If I understand it correctly, I might have something useful to add. I've given a name to what the OP describes, that being the process of using SQL from a query saved in an ACCDB to run in VBA via DAO or ADOBD. The name I've given it is "Object Property Provider", even with the acronym OPP in my notes, and for the object name prefix/suffix.
The idea is an existing object in an ACCDB (usually a query) provides a property (usually SQL) that you need to use in VBA. I slapped together a function just to suck SQL out of queries for this; see below. Forewarning: sorry, but this is all in DAO, I don't have much use for ADODB. Hope you will still find the ideas useful.
I even went so far as to devise a method of using/inserting replaceable parameters in the SQL that comes from these OPP queries. Then I use VBA.Replace() to do the replacing before I use the SQL in VBA.
The DAO object path to the SQL of a query in an ACCDB is as follows:
mySqlStatement = Access.Application.CurrentDb.QueryDefs("myQueryName").SQL
The way I use replaceable parameters is by evaluating what needs to be replaced, and choosing an unusual name for the paramater that cannot possibly exist in the real database. For the most part, the only replacements I've made are field or table names, or the expressions of WHERE and HAVING clauses. So I name them things like "{ReplaceMe00000001}" and then use the Replace() function to do the work...
sqlText = VBA.Replace(sqlText, "{ReplaceMe00000001}", "SomeActualParameter")
...and then use the sqlText in VBA. Here's a working example:
Public Function MySqlThing()
Dim sqlText as String
Dim myParamater as String
Dim myExpression as String
'Set everything up.
sqlText = getSqlTextFromQuery("myQuery")
myParameter = "{ReplaceMe00000001}"
myExpression = "SomeDateOrSomething12/31/2017"
'Do the replacement.
sqlText = VBA.Replace(sqlText, myParameter, myExpression)
'Then use the SQL.
db.Execute sqlText, dbFailOnError
End Function
Function getSqlTextFromQuery(ByVal oppName As String) As String
Dim app As Access.Application
Dim db As DAO.Database
Dim qdefs As DAO.QueryDefs
Dim qdef As DAO.QueryDef
Dim sqlText As String
Set app = Access.Application
Set db = app.CurrentDb
Set qdefs = db.QueryDefs
Set qdef = qdefs(oppName)
oppGetSqlText = qdef.SQL
End Function

Excel VBA SQL Data

I have a small excel program.
I would like to be able to use this program to update a SQL table.
What would be the function to say update line 2 in SQL table Test in Database ABC
Thanks
First of all you need to add a reference to the ActiveX Data Objects library, which contains the set of objects that allow you to do database access - in the Excel Visual Basic editor, go to Tools|References... In the dialog box, scroll down until you find Microsoft ActiveX Data Objects 2.8 Library. Check the box next to the library name.
VBA References dialog with ADO library checked http://philippursglove.com/stackoverflow/adoreference.png
Your code to update the database should then look something like this (using the SQL from JohnK813's answer):
'Declare some variables
Dim cnn As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New ADODB.Connection
'Set the connection string
cnn.ConnectionString = myDatabaseConnectionString 'See http://connectionstrings.com if you need help on building this string for your database!
'Create a new Command object
Set cmd = New ADODB.Command
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE Test SET YourField = NeValue WHERE IDField = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
I see you have other questions open that deal with actually connection to the SQL Server, so I won't add any more to that discussion.
Relational database tables don't think of things as being in a certain order, so you can't really say that a certain record is "record 2" or "line 2" just because you added it to the table second. Unless of course you use a field to create an ID number that increments with each new record added.
Then you can access that record by saying
UPDATE Test SET YourField=NewValue WHERE IDfield=2
Here's more information on the UPDATE command, if you need it.

How to make a parametrized SQL Query on Classic ASP?

Can someone show me the simplest way of perform a parametrized SQL query using Classic ASP in VBscript?
A compilable example would be best.
Use the adodb.command object.
with createobject("adodb.command")
.activeConnection = application("connectionstring")
.commandText = "select * from sometable where id=?"
set rs = .execute( ,array(123))
end with
I would also advise to use a custom db access object instead of using adodb directly. This allows you to build a nicer api, improves testability and add hooks for debuging/logging/profiling. Secondly you can add request scoped transactions with implicit rollback's on errors using the class_terminiate event. Oure db access object offers the following query api
call db.execute("update some_table set column=? where id=?", array(value, id))
set rs = db.fetch_rs("select * from some_table where id=?", array(id))
count = db.fetch_scalar("select count(*) from some_table where column > ?", array(value))
I'm assuming you are referring to a parameterized SQL Query. If this is the case, then the VBScript code would look something like this:
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open "connectionstring"
SET cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = adoCon
cmd.CommandType= adCmdStoredProc
cmd.CommandText = "GetCustomerByFirstName"
cmd.Parameters.Append cmd.CreateParameter("#FirstName",adVarchar,adParamInput,50,"John")
Set Rec = cmd.Execute()
While NOT Rec.EOF
'code to iterate through the recordset
Rec.MoveNext
End While
UPDATE: You need to include the ADOVBS.inc file for the constants to be recognized.
Here's a link: ADOVBS.inc
Another option to including adovbs.inc is to add a reference to the following type library near the top of your ASP. Supposedly this has better performance than an include:
<!--METADATA TYPE="TypeLib" NAME="ADODB Type Library" UUID="00000205-0000-0010-8000-00AA006D2EA4" FILE="C:\Program Files\Common Files\System\ado\msado15.dll" VERSION="2.5" -->
Here is a list of some type libraries.