I have the follow data in a column:
aud_344266_jayde_adams
int_343581_jtou_s5_ep1
of_344289_geordie_s21_rig_c
soft_343726_24hrpc_s4_norbiton
on_334195_sas_s5_1007_1008
and I only want to return the following:
344266
343581
344289
343726
334195
As you can tell there is a pattern in the number I want to return. They have to underscore before and after them and also have a length of 6 characters.
Is there any way of doing this in SQL Server?
For your example data, this works:
select left(stuff(t.col, 1, patindex('%[_][0-9][0-9][0-9][0-9][0-9][0-9][_]%', t.col), ''), 6)
Or even more simply:
select substring(t.col, patindex('%[_][0-9][0-9][0-9][0-9][0-9][0-9][_]%', t.col) + 1, 6)
Here is a db<>fiddle.
You can use left, right and charindex function
example:
declare @row as varchar(100) = 'aud_344266_jayde_adams'
select @row, right(@row, len(@row)-charindex('_',@row)), left(right(@row, len(@row)-charindex('_',@row)),-1 + charindex('_',right(@row, len(@row)-charindex('_',@row))))
For your table you do:
select left(right(_Column, len(_Column)-charindex('_',_Column)),-1 + charindex('_',right(_Column, len(_Column)-charindex('_',_Column))))
From Tbl
APPLY
is your friend.
-- Sample Data
DECLARE @yourtable TABLE (SomeString VARCHAR(100));
INSERT @yourtable (SomeString) VALUES
('aud_344266_jayde_adams'),('int_343581_jtou_s5_ep1'),('of_344289_geordie_s21_rig_c'),
('soft_343726_24hrpc_s4_norbiton'),('on_334195_sas_s5_1007_1008');
-- Solution
SELECT TheNumber = SUBSTRING(t.SomeString,d1.Pos,d2.Pos-d1.Pos)
FROM @yourtable AS t
CROSS APPLY (VALUES(CHARINDEX('_',t.SomeString)+1)) AS d1(Pos)
CROSS APPLY (VALUES(CHARINDEX('_',t.SomeString,d1.Pos))) AS d2(Pos);
Returns:
TheNumber
----------
344266
343581
344289
343726
334195
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.