Reputation: 21
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?
Upvotes: 0
Views: 74
Reputation: 1269633
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.
Upvotes: 3
Reputation: 14208
You can use SUBSTRING combine with CHARINDEX to achieve it
select substring(value, CHARINDEX('_', value) + 1, 6)
from TempTable
Output
344266
343581
344289
343726
334195
Upvotes: 1
Reputation: 7918
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
Upvotes: 1
Reputation: 4061
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
Upvotes: 1