Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SQL 'LIKE' Statment that looks for specific Patterns of numbers and letters

Is it possible to use LIKE in a SQL query to look for patterns of numbers and letters. I need to locate all records where the specific field data has the pattern (2 Numbers,1 hyphen, 3 Letters) ## - AAA I am using SSMS with SQL Server 2008. Any help would be appreciated. THANKS.

like image 981
user234872 Avatar asked Jun 16 '10 15:06

user234872


People also ask

How do I find a specific pattern in SQL?

LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query. LIKE clause searches for a match between the patterns in a query with the pattern in the values present in an SQL table.

How do I create a SQL pattern?

SQL pattern matching can be done using the LIKE operator. _ is used to match a single element and % is used to match an arbitrary number of elements. The NOT operator is used to select elements that do not match the given pattern.

Which command do we use to check patterns in SQL like similar like pattern?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters.

Can SQL like be used for numbers?

The LIKE operator is used in the WHERE condition to filter data based on some specific pattern. It can be used with numbers, string, or date values.


2 Answers

I think LIKE '%[0-9][0-9]-[A-Z][A-Z][A-Z]%' should work.

I'm not sure of your case sensitivity requirements but you can stick a COLLATE in as below.

select * from
(
SELECT 'GHSASKJK' AS T UNION ALL
SELECT 'HGGH11-ABC'  UNION ALL
SELECT 'HGGH11-abc' 
) f
WHERE T LIKE '%[0-9][0-9]-[A-Z][A-Z][A-Z]%' COLLATE Latin1_General_CS_AS
like image 110
Martin Smith Avatar answered Oct 23 '22 10:10

Martin Smith


You should also be able to accomplish this with PATINDEX.

Select *
From Table
Where PatIndex( '%[0-9][0-9]-[A-Z][A-Z][A-Z]%', Value) > 0
like image 27
Thomas Avatar answered Oct 23 '22 10:10

Thomas