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.
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