简体   繁体   中英

Extracting a number of specific length from a string in SQL Server

I have a string like

ADN120_XK7760069988881LJ 

in one of my columns. I have to extract the number with 13 digits length. For example, in the above case, I want to extract 7760069988881 in SQL Server.

using patindex() with substring() (using a variable for the pattern and replicate() to simplify repeating [0-9] 13 times):

create table t (val varchar(128));
insert into t values ('ADN120_XK7760069988881LJ');

declare @pattern varchar(128) = '%'+replicate('[0-9]',13)+'%';

select substring(val,patindex(@pattern,val),13)
from t;

rextester demo: http://rextester.com/MOEVG64754

returns 7760069988881

Creating TEMP table with your query

SELECT 'ADN120_XK7760069988881LJ' CODE INTO #TEMP

Solution using regular expression

SELECT SUBSTRING(CODE,PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',CODE),13)
FROM #TEMP

Couldn't reduce the number of times [0-9] used

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM