FIX: Getting Select Distinct To Work Under ADO with SQL ServerID: Q181479
|
Under certain conditions with ActiveX Data Objects (ADO), SELECT DISTINCT
in your SQL statement will not provide distinct records.
Any of the following situations produces incorrect results with SQL
Server:
The reason this does not work with adUseClient is that ADO uses SQL Server's FOR BROWSE option on the SQL statement to get extended metadata in order to process updates. The use of this option causes SQL version 6.5 to ignore the DISTINCT keyword.
Here are the two possible techniques you can use to get SELECT DISTINCT to work as expected:
This bug was corrected in ActiveX Data Objects, version 2.0.
Option Explicit
Dim conn As New Connection
'Dim com As New Command 'Uncomment to make DISTINCT work.
Dim rs As New Recordset
Private Sub Command1_Click()
conn.open "mymachine", "sa", ""
conn.cursorlocation = adUseClient 'Change to aduseServer.
'com.ActiveConnection = conn 'Uncomment to make DISTINCT work.
rs.open "select distinct state from authors", conn, _
adOpenKeyset, adLockOptimistic
MsgBox rs.RecordCount
End Sub
Private Sub Command2_Click()
Dim counter As Integer
counter = 0
conn.Open "dsn=mymachine;id=sa;pwd=;"
com.ActiveConnection = conn
conn.CursorLocation = adUseClient 'Comment this
'conn.CursorLocation = adUseServer 'and uncomment this.
com.CommandText = "select distinct state from authors"
com.CommandType = adCmdText
rs.CursorType = adOpenKeyset
'cursortype will be adopenforwardonly with adUseServer.
Set rs = com.Execute
While Not rs.EOF
Debug.Print rs!State
counter = counter + 1
rs.MoveNext
Wend
Debug.Print "--------------------"
MsgBox counter 'recordcount return -1 with adUseServer
End Sub
For additional information, please see the following article in the
Microsoft Knowledge Base:
Q172115 BUG: DISTINCT with NO_BROWSETABLE Returns Duplicate Rows
Additional query words: kbdse kbcrossref
Keywords : kbcode kbADO100 kbADO150
Version : WINDOWS:1.0,1.5
Platform : WINDOWS
Issue type : kbbug
Last Reviewed: February 25, 1999