I've scoured multiple forums for days now and still stuck. Hoping somebody can shed some light here.
I am increasingly frustrated by SQL syntax differences between MS Office and native SQL, and I've been led to believe that using pass through queries will allow me to use native SQL. I've tried multiple suggestions from various forums to create a pass through query, but I am still faced with Office (syntax) errors in my queries.
Below is a simple example of my code, which Excel/VBA does not like, due to the ISNULL syntax. Please note, it isn't ISNULL itself that is the problem, I know how to work around that. This is just by way of example. The problem is that it should work in native SQL (and it does in SQL Server Management Studio).
For completeness, I am using:
SQL Server 2014
MS Excel 2013
Microsoft DAO 3.6 Object library
I suspect the connection string or the DAO object library may be the culprit, but I've tried multiple others with the same result.
The complete sample (failing on OpenRecordSet) code follows. I would be eternally grateful for any help that can be offered.
Thanks, Ryan
Option Explicit
Sub TestQuerySQL()
Dim sqlConnect As String, dsnName As String, dbName As String, sqlString As String, db As Database, qd As QueryDef, rs As Recordset
dsnName = "MyDSN"
dbName = "MyDatabaseName"
sqlConnect = "ODBC;DSN=" & dsnName & ";Trusted_Connection=yes;"
sqlString = "Select isnull(d.Name, '???') as DealerName from Dealer d"
Set db = OpenDatabase(dbName, dbDriverNoPrompt, True, sqlConnect)
On Error Resume Next
Set qd = db.CreateQueryDef("", sqlString)
If Err.Number <> 0 Then
MsgBox "CreateQueryDef failed. SQL=>" & sqlString & "< " & Err.Number & " Err=>" & Err.Description & "<", vbCritical
Else
qd.ReturnsRecords = True
Set rs = qd.OpenRecordset(dbOpenSnapshot, dbReadOnly)
If Err.Number <> 0 Then
MsgBox "OpenRecordset Failed. SQL=>" & sqlString & "< Err=>" & Err.Description & "<", vbCritical
Else
MsgBox "Success"
'do someting with the results
End If
End If
End Sub
ISNULL()is used in Access and MSSQL but in different implementations. For Access, this function with no arguments returns true/false but not SQL Server. Are you connecting to SQL Server or an .mdb/.accdb database? If former, your query is valid. If latter, your error will emerge.