Fixing ODBC Filter Strings
Posted
by Dean Grimm
on May 17th, 1999
The first parameter is a NULL terminated string that contains the text string that will be reformatted. Also, if parameter bIsLike is TRUE, then all occurrences of the underscore & percent characters are surrounded by square brackets (a_b.ps becomes a[_]b.ps). This causes ODBC to view these characters as non-wildcards.
Following is a short example of how SQLFix might be used in your code:
BOOL GetARecord()
{
CString strName(_T("Fred's Bank"));
CString strPath(_T("a_b.ps"));
CMyRecordset myset;
myset.m_strFilter.Format(_T("[Name] = '%s' and [Path] Like '%%\\%s'"),
SQLFix(strName), SQLFix(strPath, TRUE));
if (myset.Open())
...
}
In the above example, myset.m_strFilter would be "[Name] = 'Fred''s Bank'
and [Path] Like '%%\\a[_]b.ps"
And here's the function:
CString SQLFix(LPCTSTR szText, BOOL bIsLike = FALSE)
// escapes illegal ODBC characters '%_
{
// quickly determine if we have illegal characters
if (_tcschr(szText,_T('\'')) == NULL
&& (!bIsLike || _tcspbrk(szText,_T("%_")) == NULL))
return CString(szText);
// Searches for "'" and replaces it with "''"
CString strTemp("");
int nLength = _tcslen(szText);
bool bDoLike;
for ( register int count = 0 ; count < nLength ; count++ )
{
// % and _ must be surrounded by square brackets in a LIKE statement
bDoLike = (bIsLike && (szText[ count ] == _T('_') || szText[ count ] == _T('%')));
if (bDoLike)
strTemp += _T('[');
// add the source character
strTemp += szText[ count ];
// single quotes must be escaped with a second single quote
if( szText[ count ] == _T('\'') )
strTemp += _T('\'');
if (bDoLike)
strTemp += _T(']');
}
return strTemp;
}
Date Last Updated: May 17, 1999

Comments
How can i use m_strFilter with date?
Posted by Legacy on 04/11/2003 12:00amOriginally posted by: dkjf
How can i use m_strFilter with date?
Replyhow can i conect to the Sqlserver2000 with odbc?
Posted by Legacy on 12/11/2002 12:00amOriginally posted by: andychang
ReplyWrong way!
Posted by Legacy on 01/25/2000 12:00amOriginally posted by: Daniel Cyr
ReplyA doubt and a little addendum ...
Posted by Legacy on 05/26/1999 12:00amOriginally posted by: Homero de la Garza
ReplySame problem, with DAO
Posted by Legacy on 05/19/1999 12:00amOriginally posted by: Daniel MOSMONDOR - Mosh
I had a similar problem when using DAO, but mainly it was usage of " and ' characters that made problems. I see that you manualy change _ to [_] but you can use CString::Replace function instead.
Reply