Search code examples
sqlsql-serversql-server-2008sql-like

How to ignore left padding in a LIKE statement?


I'm modifying code for an ID search bar and I'm trying to enable the user to be able to search for ID's using SQL syntax, so for example '%535%'. Doing just that is simple enough, but I've been searching and racking my brains for a while now and I can't seem to find a solution to the issue described below:

The problem is that the IDs are all left-padded varchar(14), as in:

'          8534'
'        393583'
'    123456/789'

This virtually disables the user from searching only for IDs that begin with a certain sequence, as '85%' returns no results due to the whitespace padding.

The site I'm maintaining is an oldie written in classic ASP (w/ JScript) and the search is done via a stored procedure with the whole 'WHERE' clause being passed in as a parameter.

I'm not able to modify the database, so what I"m asking is: is there any way to modify the clause so that the padding is ignored and '52%' returns IDs beginning with 52?


Solution

  • Functions in the where clause tend to be slow. Something like this might be quicker:

    where id like '123%'
    or id like '% 123%'