在进一步研究这个问题后,我想出了 -->
-- partition into non-num and numeric strings, collapse non-num into single space, and copy numeric as is
-- complicating: multiple non-num and multiple numeric strings
-- further, allow for starting with EITHER non-num or numeric
-- further, can have no numeric at all, or can have no non-num at all
我将数据放入表 dbo.separatenumber
并创建了UDF--> Revised Jan 15th--del If/Then/Set @next, add Set @LeftMost
/****** Object: UserDefinedFunction [dbo].[fnSeparateNonNumericCharacters] Script Date: 01/14/2020 21:41:42 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnSeparateNonNumericCharacters]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnSeparateNonNumericCharacters]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[fnSeparateNonNumericCharacters](@strText VARCHAR(1000)) RETURNS VARCHAR(1000) AS
BEGIN
Declare @outText as varchar(1000), @LeftMost as char(4), @ndx as int
Set @outText = ''
IF PATINDEX('[0-9]', SUBSTRING(@strText,1,1)) = 1 -- is the 1st char numeric?
Set @LeftMost = 'Nums'
ELSE
Set @LeftMost = 'Text'
;
WHILE LEN(@strText) > 0
BEGIN
IF @LeftMost = 'Text'
BEGIN
Set @ndx = PATINDEX('%[0-9]%', @strText) -- where is the next Numeric
If @ndx = 0 Break -- bail when no more
Set @strText = SUBSTRING(@strText, @ndx, LEN(@strText) - @ndx + 1) -- bypass Text
Set @LeftMost = 'Nums'
END
ELSE -- @LeftMost = 'Nums'
BEGIN
Set @ndx = PATINDEX('%[^0-9]%', @strText) -- where is next Text
If @ndx = 0 Set @ndx = LEN(@strText) + 1 -- use EOL plus one when no more
Set @outText += SUBSTRING(@strText, 1, @ndx - 1) + ' ' -- Grab Numbers plus a space
If @ndx = LEN(@strText) + 1 Break -- bail when no more
Set @strText = SUBSTRING(@strText, @ndx, LEN(@strText) - @ndx + 1 ) -- move past this Num
Set @LeftMost = 'Text'
END
;
END
RETURN @outText -- here it is
END
GO
select
*
, dbo.fnSeparateNonNumericCharacters(clientname) as Numbers
from dbo.separatenumber
样本输出
ClientID ClientName Numbers
11 Mukherjee_ 2697231 Gehrmann _ 298053524 2697231 298053524
22 Butt Glen_740708968 Amanda_259055000 740708968 259055000
33 Quirk Michael_ 65941412 and Leanne _817498908 65941412 817498908
44 Butt Glen_740708968 Amanda_259055000 Tristan 3939393939 740708968 259055000 3939393939
55 Kryger Aaron _ 606506375 606506375
66 Krebs Paul
77 Haddrill Clare _ 333900499 McRedmond Patrick _557887778 333900499 557887778