Wednesday, March 28, 2012

Valid Access Query Creates Empty Table using OleDbCommand?

I have a very simple query which runs through the Northwind customers table and extracts all CustomerIDs who live in a city starting with 'P'. It works great if I double-click on it in Access, but when I run it through my VB code, an empty table is created. Any idea what is going on?

Here is the very simple query text, which works well in MS Access, called 'MyQuery':

SELECT DISTINCT Customers.CustomerID, Customers.City INTO pCityCustomerIDs
FROM Customers
WHERE (((Customers.City) Like "P*"));

Here is my very simple VB Code:

Public Function ExecuteProcedure(ByVal sFileLocation As String) As Integer

Dim dcMSAccessConnection As OleDb.OleDbConnection = New OleDb.OleDbConnection( _

"Provider= Microsoft.Jet.OLEDB.4.0;Data Source=" & sFileLocation)

Dim myCmd As New OleDb.OleDbCommand

myCmd.CommandText = "MyQuery"

myCmd.CommandType = CommandType.StoredProcedure

myCmd.Connection = dcMSAccessConnection

Dim rowsAffected As Integer

' Open Connection, run the query, then close the connection

dcMSAccessConnection.Open()

rowsAffected = myCmd.ExecuteNonQuery

dcMSAccessConnection.Close()

Return rowsAffected

End Function


Under ADO (Jet OLEDB) the wildcard character is a percent sign. The asterisk is specific to DAO and Microsoft Access.

SELECT DISTINCT Customers.CustomerID, Customers.City INTO pCityCustomerIDs
FROM Customers
WHERE (((Customers.City) Like "P%"));


try with:

myCmd.ExecuteReader


Thanks Paul,

The devil is in the details.

No comments:

Post a Comment