Is there an operator or an easy way to match an expression one or more times with the LIKE operator in SQL?
-
16-02-2021 - |
문제
For example if I run the following query, the expression in the WHERE clause will only match on the first letter before a number but is there a way to match on one or more letters first (e.g. in the case where there's a variable number of letters before the number in the field I'm filtering on)?
SELECT FilteredField
FROM Table
WHERE FilteredField LIKE '[a-zA-Z][0-9]'
Example data:
- ABC9
- DEF2
- GH7
- Z1
- XYH2
Essentially I'm looking for the SQL Server 2016 equivalent of the RegEx + when using the LIKE operator.
해결책
If you are talking about solving this purely in Transact-SQL, you can cover all those cases in your example data with the following filter:
WHERE FilteredField LIKE '%[a-zA-Z][0-9]'
If you want to additionally stipulate that all the characters before the numeral must be Latin letters, you will need to get a little creative:
WHERE FilteredField LIKE '%[a-zA-Z][0-9]'
AND FilteredField NOT LIKE '%[^a-zA-Z]%[a-zA-Z][0-9]'
Basically, you are saying:
The value must end with a letter and a numeral, but whatever precedes the letter must not be a non-letter.
There is no way to specify this with a single condition using only built-in syntax, if that was what you were after.
다른 팁
As said by mustaccio in comments:
Is there anything that prevents you from using a proper regular expression implementation instead of trying to hack around LIKE?
There's an option to use CLR, Common Language Runtime, basically you create some C# functions, and you import it in your SQL server, from there on you can just call a SQL function, and it will execute your C# code for you.
This naturally gives you all the possibilies you have in .NET regex, straight from your SSMS.
There's a ton of different resources on how to go about this.
Red gate regex assembly
Code project example