Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Regex for 7 digit number in varchar field

Question:
What’s the best way to ‘extract’ all Rows where the TEXT column contains a 7 digit number starting with 7 and only show the 7 digit number?

MS SQL Server 2017:

CREATE TABLE [TABLE_1] (
TEXT varchar(50) Null,
);

INSERT INTO TABLE_1
(TEXT)
VALUES
('7005011'),
('The Number is 7335022'),
('asd*.-: wqe'),
('/7225033/.123'),
('Nr.: 7115044')
;

SQL Fiddle Link

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The desired result would be:

+---------+
| TEXT    |
+---------+
| 7005011 |
| 7335022 |
| 7225033 |
| 7115044 |
+---------+

>Solution :

There’s no RegEx in SQL Server natively, you need to use PATINDEX, SUBSTRING, and LIKE:

SELECT [TEXT] = SUBSTRING([TEXT], 
  PATINDEX('%' + REPLICATE('[0-9]', 7) + '%', [TEXT]), 7)
FROM dbo.TABLE_1
WHERE [TEXT] LIKE '%' + REPLICATE('[0-9]', 7) + '%';

Output:

TEXT
7005011
7335022
7225033
7115044
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading