Search code examples
sqlvbadb2adodb

DB2 VBA How do I SET System Variables within a SQL String Query without error?


This query fails when used in a SQL string from VBA, the Recordset simply remains closed:

SET CURRENT PRECISION = 'D15.7';
SELECT 1 + 2 AS TEST FROM SYSIBM.SYSDUMMY1;

Yet this works just fine and the recordset opens as expected:

SELECT 1 + 2 AS TEST FROM SYSIBM.SYSDUMMY1;

The first exact SQL also works just fine in IBM Data Studio. Is the terminator following the precision setting, terminating the whole query? This fails in both Excel and Access VBA. I need the SET CURRENT PRECISION as I'm working with decimals up to 7 places and need the precision for percentage calculations in my real query. The version of DB2 we have (Z OS) loses the precision, otherwise. This SET statement fixes it.

I'm using IBM DB2 ODBC Driver 11.05.5000.1588, and ActiveX Data Objects 6.1 with VBA in Office 365.
Full VBA code:

Dim strConnectionString As String
Dim cnDB2Connection As ADODB.Connection
Dim cmDB2Command As ADODB.Command
Dim rsMyRecordset As ADODB.Recordset
Dim strSQLQuery As String

Set cnDB2Connection = New ADODB.Connection
Set cmDB2Command = New ADODB.Command
Set rsMyRecordset = New ADODB.Recordset
strConnectionString = "DSN=[MYODBC];Uid=" & [MYUSERNAME] & ";Pwd=" & [MYPASSWORD]
cnDB2Connection.Open strConnectionString
cmDB2Command.ActiveConnection = cnDB2Connection

strSQLQuery = "SET CURRENT PRECISION = 'D15.7';"
strSQLQuery = strSQLQuery & " SELECT 1 + 2 AS TEST FROM SYSIBM.SYSDUMMY1;"

cmDB2Command.CommandType = adCmdText
cmDB2Command.CommandText = strSQLQuery
rsMyRecordset.CursorType = adOpenStatic
rsMyRecordset.CursorLocation = adUseClient
rsMyRecordset.LockType = adLockReadOnly
rsMyRecordset.Open cmDB2Command

If Not (rsMyRecordset.BOF And rsMyRecordset.EOF) Then   'FAILS HERE as Recordset is not Open if SET CURRENT PRECISION is used...
   [DO STUFF]
END IF

Set rsMyRecordset = Nothing
Set cmDB2Command = Nothing
Set cnDB2Connection = Nothing

Expected query to run successfully. Exact same SQL with SET statement worked just fine in IBM Data Studio.


Solution

  • Thankyou @GSerg. Answer is to add the second statement (.NextRecordset):

    rsMyRecordset.Open cmDB2Command
    Set rsMyRecordset = rsMyRecordset.NextRecordset