Seeking partial strings in CDaoRecordset class

This article is related to searching character strings in text type of fields of
CDaoRecordset only. Please note that it is not applicable to other types of field data
types of DAO such as dates or numbers.

Sometimes while searching for something in CDaoRecordset object we often use Seek()
function. But the problem with the DAO is, it reports FALSE  when search is made for
partial  string. For example suppose there is record "Sharad" in the
FirstName field of table and it is indexed. If search is made for some prefix only the
return value is FALSE as shown here:

COleVariant var("Sha");

Seek("=", &var ) returns FALSE, although "Sha" is prefix of
"’Sharad".

The whole point is very relevant when we want to quickly navigate through record set as
the user types the key strokes for the item he is searching.

To get around this I have implemented a function called PartialSeek( const char
* szStr , const char * szFieldName )
as member of CDaoRecordset. To use this the
accompanying source code of this function should be added to your CDaoRecordset derived
class :

class CMyRecordset :public CDaoRecordset
{

public:

BOOL PartialSeek(const char * szStr  , const char * szFieldName ) ;

} ;

BOOL CMyRecordset::PartialSeek( const char * szStr , const char * szFieldName )

{

int nSeekResult ;
int nStrCmp;
int nLen ;
COleVariant Var(szStr , VT_BSTRT );
COleVariant Extract ;
COleVariant varBookMark ;
nLen = strlen(szStr);
varBookMark = GetBookmark();
nSeekResult = Seek("<", &Var);
MoveNext();
if (IsBOF() ||IsEOF())
    {
        SetBookmark(varBookMark);
        return 0 ;
    }
GetFieldValue(  szFieldName , Extract) ;
nStrCmp = _strnicmp(szStr, (const char *)Extract.bstrVal, nLen );
if ( nStrCmp == 0)
    {
    return TRUE ;
    }
else
    {
    SetBookmark(varBookMark);
    return FALSE ;
    }
}

 

How to call function:

Suppose the field is FirstName search key is
"Sha"

We should make call like this:
PartialSeek("Sha" , "FirstName") ;

 

Prerequisite

 

(1) This works only with text type of fields:

(2) The field must be indexed.

(3) Before using this function the index should be switched to the field we are looking
for, by making a call to SetCurrentIndex() ;

Date Last Updated: April 4, 1999

More by Author

Must Read