Skip to content

Instantly share code, notes, and snippets.

@icalderond
Created October 23, 2017 14:33
Show Gist options
  • Save icalderond/a6aa469735425ea0632486f2b2b1ba46 to your computer and use it in GitHub Desktop.
Save icalderond/a6aa469735425ea0632486f2b2b1ba46 to your computer and use it in GitHub Desktop.
Agregar un caracter en un texto cada cierto numero de caracteres
CREATE FUNCTION [dbo].[SeparaConcatenaVarchar]
(
@string VARCHAR(MAX),
@limit int,
@separator char(1)
)
RETURNS VARCHAR(MAX)
BEGIN
declare @delimiter CHAR(1)=' ';
declare @listSeparator TABLE(splitdata NVARCHAR(MAX),contador varchar(100),inicio int,fin int);
declare @valueToInsert varchar(50),@valueSplited varchar(50);
DECLARE @start INT, @end INT
declare @total int;
declare @totalRecorrido int;
declare @residuo int;
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
set @valueSplited=SUBSTRING(@string, @start, @end - @start);
set @total=len(@valueSplited)
set @totalRecorrido=0
while @totalRecorrido<=@total/@limit
begin
declare @inicio int, @fin int;
set @inicio=(@totalRecorrido*@limit)+1;
set @fin=@limit;
if @totalRecorrido<@total/@limit and @totalRecorrido=0
set @inicio=1;
if @totalRecorrido=(@total/@limit) and @total%@limit>0
set @fin=(@total%@limit)+1;
set @valueToInsert=substring(@valueSplited,@inicio,@fin);
INSERT INTO @listSeparator VALUES(@valueToInsert,@valueSplited,@inicio,@fin);
set @totalRecorrido=@totalRecorrido+1
end
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
end
RETURN STUFF((SELECT @separator + splitdata FROM @listSeparator FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment