Search code examples
pymssql

SQL Server starts with list of strings


I was previously using MySQL and had a query which used a REGEXP. I'm trying to find site_ids beginning with certain characters, and used the following:

WHERE site_id REGEXP '^(AB|BC|AO|BO|CA|PAF|Z)'

Basically trying to find rows where site_id LIKE 'AB%' OR 'BC%'..., but because I have quite a few strings to match against, I'd like to do it in a less verbose manner.

Unfortunately SQL Server doesn't seem to like this syntax and I get an error:

An expression of non-boolean type specified in a context where a condition is expected, near 'REGEXP'.DB-Lib error message 4145, severity 15: General SQL Server error: Check messages from the SQL Server

Is there a neat way of doing this without using heaps of LIKE 'XX%' OR ...?


Solution

  • You can use a combination of left, or, and in to shorten your query.

    WHERE left(site_id,2) in ( 'AB', 'BC', 'AO', 'BO', 'CA') or left(site_id, 3) = 'PAF' or left(site_id, 1) = 'Z'