我在db中有一个字符串值。我需要在每3个字符之间插入一个,
。这是示例字符串。在Sql Server中分成3个字符
样品字符串
111100120125 // This sample is a dynamic string. So It can be less or more ..
结果
Val = 111,100,120,125
请告诉我内建SqlServer的函数来获取,
分隔字符串作为结果。
任何帮助,将不胜感激。
谢谢。
我在db中有一个字符串值。我需要在每3个字符之间插入一个,
。这是示例字符串。在Sql Server中分成3个字符
样品字符串
111100120125 // This sample is a dynamic string. So It can be less or more ..
结果
Val = 111,100,120,125
请告诉我内建SqlServer的函数来获取,
分隔字符串作为结果。
任何帮助,将不胜感激。
谢谢。
您可以使用递归CTE:
declare @f varchar(100)='111100120125'
;with pos as(
select 3 n, cast(SUBSTRING(@f,1,3) as varchar(max)) a
union all
select n+3 n, a+','+ SUBSTRING(@f,n+1,3) from pos
where n<LEN(@f)
)
select max(@f) ini, max(a) res from pos;
请告诉我关于SqlServer的内置函数来获取 分隔字符串的结果。
您可以使用Stuff()函数。 特定于您的给定字符串。
Declare @S varchar(50) = '111100120125'
SELECT STUFF(STUFF(STUFF(@S,4,0,','),8,0,','),12,0,',')
111,100,120,125
编辑:更通用的解决方案是创建像下面的函数(注意,这个功能开始插入从端分离器的值):
CREATE FUNCTION dbo.AddSeparator (@String VARCHAR(max), @Separator VARCHAR(1))
RETURNS VARCHAR(max)
AS
BEGIN
Declare @Length int = Len(@String)
WHILE (@Length > 3)
BEGIN
SELECT @String = STUFF(@String, @Length - 2, 0, @Separator),
@Length = @Length -3
END
RETURN @String
END;
用法fiddle demo:
SELECT String Original, dbo.AddSeparator(String, ',') Modified
FROM T
结果:
| ORIGINAL | MODIFIED |
|----------|-----------|
| | |
| 1 | 1 |
| 12 | 12 |
| 123 | 123 |
| 1234 | 1,234 |
| 12345 | 12,345 |
| 123456 | 123,456 |
| 1234567 | 1,234,567 |
字符串“111100120125”可以是动态的。所以我想知道字符串分离的动态级别。 – DonMax
难道只是一个字符串变量或表字段?并且在字段/变量中是否有最大可能的长度? – Kaf
我认为最好的方法是创建一个CLR UDF--除非可能的值是非常窄的范围。 –
它的一个表值和它的varchar(200)类型。 – DonMax