1

Ts there a way to extract numbers from a string?

In my database there is a column called Reference and it contains multiple numbers

CM|319|14163|||109|405000

Is there a way to get the first number like this?

select CM|%s|... as ParentId from table

So the output should be 319

And maybe even multiple like

select CM|...|%s|... as SiblingId, CM|%s|... as ParentId from table

14163 319

3
  • What is your DB? Commented Aug 23, 2021 at 7:16
  • Which dbms are you using? (Many products have their own, non-ANSI, string functions.) Commented Aug 23, 2021 at 7:16
  • Im using microsoft sql studio I think its mssql but im not sure Commented Aug 23, 2021 at 7:19

2 Answers 2

3

We might be able to use PATINDEX here along with a substring operation. We can find the position of the first number in the string, and then take a substring until one position past the first occurrence of a number followed by a pipe character.

SELECT SUBSTRING(val,
                 PATINDEX('%[0-9]%', val),
                 PATINDEX('%[0-9]|%', val) - PATINDEX('%[0-9]%', val) + 1)
FROM yourTable;

Demo

Data:

WITH yourTable AS (
    SELECT 'CM|319|14163|||109|405000' AS val
)
Sign up to request clarification or add additional context in comments.

Comments

0

if using sql2017 or later... maybe?

CREATE TABLE #yourtable(
   reference VARCHAR(50) NOT NULL PRIMARY KEY
);
INSERT INTO #yourtable(reference) VALUES ('CM|319|14163|||109|405000');
INSERT INTO #yourtable(reference) VALUES ('CMff123|14163|||109AA|4ZXC05000');


SELECT reference,
       TRIM(REPLACE(TRANSLATE(reference,'abcdefghijklmnopqrstuvwxyz',REPLICATE('|',26)),'|',' ')) AS extracted
FROM #yourtable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.