Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat LIKE pattern 'n' times

Tags:

sql-server

I would like repeat LIKE pattern 7 times in my queries.

SELECT count(displayName),
AS nbDisplayNameDefaut
FROM users
WHERE displayName LIKE 'user[0123456789]'

This query return all display name like userX but i would like to have seven time numbers to have display name like this userXXXXXXX (X is numbers)

I think that this query is not optimized if I make this :

LIKE 'user[0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789]'

I don't find the option in SQL-Server doc

like image 797
Mattasse Avatar asked Feb 06 '23 12:02

Mattasse


1 Answers

SQL Server LIKE supports range patterns so you can use [0-9] instead of [01234567899] for a single decimal digit. This pattern can be replicated for the number of digits desired for a more concise expression:

LIKE 'user' + REPLICATE('[0-9]', 7)
like image 56
Dan Guzman Avatar answered Feb 16 '23 09:02

Dan Guzman