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')
;
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 |
- Example db<>fiddle