我的问题非常简单。我从sql select中得到一个如下所示的值:
ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG
我需要这样:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO,FI,FR,GE,GR,IE,IS,IT,JP,YU,CA,KZ,KG
每个数据集的长度不同。 我尝试使用format(),stuff()等等,但没有给我带来我需要的结果。
提前致谢
答案 0 :(得分:2)
更新简历的时间。
create function DontDoThis (
@string varchar(max),
@count int
)
returns varchar(max)
as
begin
declare @result varchar(max) = ''
declare @token varchar(max) = ''
while DATALENGTH(@string) > 0
begin
select @token = left(@string, @count)
select @string = REPLACE(@string, @token, '')
select @result += @token + case when DATALENGTH(@string) = 0 then '' else ',' end
end
return @result
end
呼叫:
declare @test varchar(max) = 'ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG'
select dbo.DontDoThis(@test, 2)
答案 1 :(得分:2)
在numbers table和for xml path
的帮助下。
-- Sample table
declare @T table
(
Value nvarchar(100)
)
-- Sample data
insert into @T values
('ARAMAU'),
('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG')
declare @Len int
set @Len = 2;
select stuff(T2.X.value('.', 'nvarchar(max)'), 1, 1, '')
from @T as T1
cross apply (select ','+substring(T1.Value, 1+Number*@Len, @Len)
from Numbers
where Number >= 0 and
Number < len(T1.Value) / @Len
order by Number
for xml path(''), type) as T2(X)
试试SE-Data
答案 2 :(得分:1)
答案 3 :(得分:1)
我相信这就是QQping正在寻找的。 p>
-- select .dbo.DelineateEachNth('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',2,',')
create function DelineateEachNth
(
@str varchar(max), -- Incoming String to parse
@length int, -- Length of desired segment
@delimiter varchar(100) -- Segment delimiter (comma, tab, line-feed, etc)
)
returns varchar(max)
AS
begin
declare @resultString varchar(max) = ''
-- only set delimiter(s) when lenght of string is longer than desired segment
if LEN(@str) > @length
begin
-- continue as long as there is a remaining string to parse
while len(@str) > 0
begin
-- as long as know we still need to create a segment...
if LEN(@str) > @length
begin
-- build result string from leftmost segment length
set @resultString = @resultString + left(@str, @length) + @delimiter
-- continually shorten result string by current segment
set @str = right(@str, len(@str) - @length)
end
-- as soon as the remaining string is segment length or less,
-- just use the remainder and empty the string to close the loop
else
begin
set @resultString = @resultString + @str
set @str = ''
end
end
end
-- if string is less than segment length, just pass it through
else
begin
set @resultString = @str
end
return @resultString
end
答案 4 :(得分:1)
select Wow=
(select case when MatchIndex %2 = 0 and MatchIndex!=0 then ',' + match else match end
from dbo.RegExMatches('[^\n]','ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',1)
for xml path(''))