SQL Server - Line Break

Asked

Viewed 1,414 times

0

Good morning, thank you for the time in reading that question.

Problem !


Consider the registration line ID | Nome 1 | "Fulano 1, Fulano 2, Fulano 3, Fulano 4"

I need to mount a select that when it works, returns: ID | Nome 1 | "Fulano 1" 1 | "Fulano 2" 1 | "Fulano 3" 1 | "Fulano 4"

There are other details that I will have to turn myself still rsrsrs, because this comma was only a basic example that I gave, because I will have to face other problems like char(13), only spaces, nomenclatures "or", example:

ID | Nome 1 | "Fulano 1**char(13)** Fulano 2**char(13)** Fulano 3 **char(13)** Fulano 4" 2 | "Fulano 1 Fulano 2 Fulano 3" 3 | "Fulano 1 **ou** Fulano 2"

PS. The name quantity per record is variable, as examples

I apologize if the doubt is unclear. I thank you all.

  • what version of SQL Server is using?

  • @Ricardopontual, SQL Server 2014!

  • @jeovanithomazini I suggest reading the article "Separating multi-valued text content (string split)", where you will find efficient ways to get what you need. = > https://portosql.wordpress.com/articles/

1 answer

1


You can use this function according to your delimiter ('**',',',..)

CREATE FUNCTION [dbo].[SDF_SplitString]
(
    @sString nvarchar(2048),
    @cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
    if @sString is null return
    declare @iStart int,
            @iPos int
    if substring( @sString, 1, 1 ) = @cDelimiter 
    begin
        set @iStart = 2
        insert into @tParts
        values( null )
    end
    else 
        set @iStart = 1
    while 1=1
    begin
        set @iPos = charindex( @cDelimiter, @sString, @iStart )
        if @iPos = 0
            set @iPos = len( @sString )+1
        if @iPos - @iStart > 0          
            insert into @tParts
            values  ( substring( @sString, @iStart, @iPos-@iStart ))
        else
            insert into @tParts
            values( null )
        set @iStart = @iPos+1
        if @iStart > len( @sString ) 
            break
    end
    RETURN

END

As of 2016 version has already available the function string_split()

  • Dear friend, I really appreciate your help. You didn’t solve the whole problem but I have a great starting point now.

  • As you have records where the delimiter can change (spaces or **), in this case you need to use a "CASE WHEN" with the CHARINDEX function to check whether or not there is that character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.