views:

52

answers:

2

I have a table in the db with one column containing a URL like http://site.com/users/*/profile

I am given a URL (like http://site.com/users/234/profile) and want to select all the rows in the db that match the url (in this case * is a wildcard).

I was thinking of using Regex to do this, by replacing the * with regex for any character. But am unsure as to what the SQL or LINQ code should be for the selection.

Do you guys have any ideas?

+5  A: 

Unless I am missing something obvious, this should just require a simple LIKE query.

SELECT *
FROM YourTable
WHERE URL LIKE 'http://site.com/users/%/'

Regex is overkill and tricky in SQL queries.

Note: The % character is the equivalent of the * wildcard in SQL expressions.

If you want to use LINQ and are only working against SQL Server, you can use this syntax:

var results =
        from yt in YourTable
        where SqlMethods.Like(yt.URL, "http://site.com/users/%/")
        select yt;
JohnFx
Is there an easy way to do that in linq? Seems they only have startswith, contains, etc...
rksprst
updated my answer to include a LINQ version.
JohnFx
+2  A: 

It's as simple as doing a like, but replacing the * character by the % character since it's the wildcard character used by T-SQL (I am assuming you are on SQL Server since this is C# and Linq related)

SELECT * 
FROM YourTable
WHERE @TheUrlIWantToMatch LIKE REPLACE(URL, '*', '%')
StevenGilligan
Like doesn't work that way. You can't have a wildcard in the expression before the LIKE keyword.
JohnFx
Oops I put them in the wrong order. I edited it thanks for pointing that out
StevenGilligan