我想在字母数字字符串中添加围绕字母的引号。例如:如果我的字符串是8AB8973,则预期输出为8'AB'8973。没有特定的模式可以出现数字和字符。我在StackOverFlow上发布了一个类似的问题,有人向我提供了以下代码,该代码适用于上面的示例。但它对于以下字符串失败了。我已经在下面的代码中提到了示例,预期输出和我收到的内容。 例如1:字符串的第一个字符是alpha = PAYGA0102。预计:'PAYGA'0102。收到的结果:PAYGA'0102 例2:字符串的最后一个字符是alpha = 00086K。预计:00086'K'。收到的结果:00086'K 例如3:所有都是chars = ADEP预期='ADEP'。收到的结果:ADEP。
我需要调整以下代码以包含上述所有条件。我稍后会循环代码,但我需要修复主要的patindex代码以满足上面提到的所有条件。下面的代码是重复的,只是为了显示我得到的不同结果。
DECLARE @position INT;
DECLARE @string VARCHAR(max);
SET @string = '9FX8173';
WHILE 1 = 1
BEGIN
SET @position = (SELECT Min(position)
FROM (VALUES (Patindex('%[^''0-9][0-9]%', @string)),
(Patindex('%[0-9][^''0-9]%', @string))) AS T(position)
WHERE T.position > 0);
IF @position IS NULL
BREAK;
SET @string = Stuff(@string, @position + 1, 0, '''');
END
PRINT @string;
SET @string = 'PAYGA0102'
WHILE 1 = 1
BEGIN
SET @position = (SELECT Min(position)
FROM (VALUES (Patindex('%[^''0-9][0-9]%', @string)),
(Patindex('%[0-9][^''0-9]%', @string))) AS T(position)
WHERE T.position > 0);
IF @position IS NULL
BREAK;
SET @string = Stuff(@string, @position + 1, 0, '''');
END
PRINT @string;
SET @string = '00086K'
WHILE 1 = 1
BEGIN
SET @position = (SELECT Min(position)
FROM (VALUES (Patindex('%[^''0-9][0-9]%', @string)),
(Patindex('%[0-9][^''0-9]%', @string))) AS T(position)
WHERE T.position > 0);
IF @position IS NULL
BREAK;
SET @string = Stuff(@string, @position + 1, 0, '''');
END
PRINT @string;
SET @string = 'ADEP'
WHILE 1 = 1
BEGIN
SET @position = (SELECT Min(position)
FROM (VALUES (Patindex('%[^''0-9][0-9]%', @string)),
(Patindex('%[0-9][^''0-9]%', @string))) AS T(position)
WHERE T.position > 0);
IF @position IS NULL
BREAK;
SET @string = Stuff(@string, @position + 1, 0, '''');
END
PRINT @string;
答案 0 :(得分:0)
使用patternSplitCM的副本很容易。而且由于该功能纯粹基于集合,因此您可以获得比任何基于RBAR的替代方案更好的性能。
针对变量的解决方案
declare @string varchar(100) = 'ABC123ZZ888X';
select newstring = replace((
select ''''+item+''''
from dbo.patternSplitCM(@string, '[0-9]')
order by ItemNumber
for xml path('')),'''''','''');
针对表格
-- sample data
declare @yourtable table (someid int identity, string varchar(100));
insert @yourtable values ('ABC'),('123X'),('BBBCC44455555ZZ6P'),('CC923PP5522'),(NULL);
-- the only difference here is that I replaced @string with t.string
select someid, oldstring = string, newstring
from @yourtable t
cross apply
( select newstring = replace((
select ''''+item+''''
from dbo.patternSplitCM(t.string, '[0-9]')
order by ItemNumber
for xml path('')),'''''','''')) addquotes
<强>结果
someid oldstring newstring
-------- ------------------- -----------------------
1 ABC 'ABC'
2 123X '123'X'
3 BBBCC44455555ZZ6P 'BBBCC'44455555'ZZ'6'P'
4 CC923PP5522 'CC'923'PP'5522'
5 NULL NULL