I have already posted two posts about extracting numbers from a string
http://beyondrelational.com/blogs/madhivanan/archive/2007/12/18/extract-only-numbers-from-a-string.aspx
http://beyondrelational.com/blogs/madhivanan/archive/2010/04/22/extracting-numbers-part-2.aspx
Loana in her blog posted a post about extracting integers from a string. Common table expression is used in the post. Here is an alternate that uses a user defined function.
Sample data
DECLARE @sample TABLE(
id INT,
data VARCHAR(200) )
INSERT @sample
SELECT 1, 'bar 1245 foo' UNION ALL
SELECT 2, 'foo 35234 bar 38383 fgh gaaaaaaaaa 84' UNION ALL
SELECT 3, 'bar 126831' UNION ALL
SELECT 4, '72348707 foo' UNION ALL
SELECT 5, 'foo bar';
Function which splits the data based on the delimiter
create function split(@data varchar(200),@delimiter char(1))
returns @splitting table (id int identity(1,1), data varchar(200))
as
begin
select @delimiter=replace(@delimiter,' ',','), @data=replace(@data,' ',',')
insert into @splitting(data)
select
substring(@data, n, charindex(@delimiter, @data + @delimiter, n ) - n)
from
(
select number as n from master..spt_values
where type='p'
) numbers
where
substring( @delimiter + @data, n, 1 ) = @delimiter
return
end
SELECT statement that concatenates the numbers
SELECT distinct
id, STUFF((SELECT
', ' + sp.data
FROM
@sample samp cross apply dbo.split(data,' ') as sp
where sp.data not like '%[^0-9]%' and samp.id=t1.id
FOR XML PATH('')), 1, 2, '' ) AS numbers
FROM
@sample as t1
The function is used to split the string and the condition used in the SELECT statement where sp.data not like '%[^0-9]%' is used to find only the numbers from the splitted string