Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSSQL pattern to match all numbers between [1-999] [closed]

I want a SQL pattern expression to match all numbers between 1 and 999.

EDIT:

In MSSQL.

like image 839
ARZ Avatar asked May 13 '12 07:05

ARZ


People also ask

How do I find the matching pattern in SQL?

SQL Pattern Matching : We can use LIKE Operator of SQL to search sub-string. The LIKE operator is used with the WHERE Clause to search a pattern in string of column. The LIKE operator is used in a conjunction with the two wildcards characters.

How do I get all the numbers between two numbers in SQL?

Type='P' filter is required to prevent duplicate numbers. With this filter the table will return numbers 0 - 2047. So "number between @min and @max" filter will work as long as the variables are within that range.

How is pattern matching done in SQL Explain with examples?

SQL pattern matching allows you to search for patterns in data if you don't know the exact word or phrase you are seeking. This kind of SQL query uses wildcard characters to match a pattern, rather than specifying it exactly. For example, you can use the wildcard "C%" to match any string beginning with a capital C.


2 Answers

When using the LIKE operator pattern-matching in SQL for a character class, there's no wildcard repeat of the character class like there is in regex. In other words, you can't do things like [0-9]+ or [0-9]{1,3} (both of these would also capture 0)

So, you have to zero-pad the number before you can compare it.

It's not directly a pattern, but this expression relies in part on the LIKE operator and will work for positive integers between 1 and 999:

RIGHT('00' + myfield, 3) LIKE '[0-9][0-9][0-9]'
AND RIGHT('00' + myfield, 3) <> '000'
AND LEN(myfield) <= 3

Edit: assumption made that you're talking about Microsoft SQL Server, since you didn't specify.

like image 174
richardtallent Avatar answered Sep 23 '22 03:09

richardtallent


SELECT * FROM table WHERE field BETWEEN 1 AND 999;

EDIT: This will work in PostgreSQL only.

If you're looking for a regexp pattern to match strings, then something like this:

SELECT * FROM table WHERE field ~ '[1-9][0-9]{1,2}';

Check out documentation on regexp patterns.

SQL Server doesn't support regular expressions as-is.
You can use the following workaround or this question: Regular Expressions in SQL Server servers?.

like image 23
vyegorov Avatar answered Sep 25 '22 03:09

vyegorov