tags:

views:

63

answers:

2

I am using an alphabetical sorting feature and need a SQL statement to return records beginning with a variable length string. However, records also need to be returned if there are periods, spaces, or dashes between any of the characters in the string.

For example, the value passed in could be "M" (easy). Or "MA" (in which case it needs to return records starting with "MA", "M.A", "M A", and "M-A"). Or "MAA", and so on.

This is the statement I have so far:

"SELECT * from table where LEFT(name," + value.Length + ")='" + value + "'"

But I can't work out how to get it to return results where there are periods, spaces or dashes in name. Any help constructing the statement would be great.

+1  A: 

Looks like a job for Regular Expressions. You can do it by returning some matching records in and applying Regex in ASP.NET & LINQ...or more efficiently, you can apply it to your SQL statement.

http://msdn.microsoft.com/en-us/magazine/cc163473.aspx

Ed B
Great link didn't even know this was possible.
MIchael Grassman
This approach requires the CLR to be enabled for the database. This is fine in many cases, but some DB administrators won't allow it. They see it as a risk.
Daniel Dyson
+1  A: 

If you're on MS SQL Server you could use the replace function if you have a reasonably finite set of "special" characters. You'll ruin index usage, but you'll likely do that anyway. For example:

SELECT
    name,
    i_will,
    never_use,
    select_star
FROM
    My_Table MT
WHERE
   REPLACE(REPLACE(REPLACE(name, '.', ''), ' ', ''), '-', '') LIKE @prefix + '%'

As you can see though, the statement quickly gets unwieldy as you add "_", "(", ")", etc...

Tom H.
Actually, if he doesn't need the special characters it woudn't completely ruin index usage.
Joel Coehoorn