0

I have a select which return 100 rows. For one of the column for some rows I get normal varchar(2) values. But in some rows I get a string like this 1}33}47}48}50}86}98}UC}AL}MH}88

I want to split the above function after delimiter } and return as rows.

can any one please help me in this.

Thanks in advance.

Szymon
  • 42,577
  • 16
  • 96
  • 114
Naveen
  • 661
  • 4
  • 10
  • 20

1 Answers1

1

First, create a simple string splitting function:

CREATE FUNCTION [dbo].[SplitString]
    (
        @List NVARCHAR(MAX),
        @Delim VARCHAR(255)
    )
    RETURNS TABLE
    AS
        RETURN ( SELECT [Value] FROM 
          ( 
            SELECT 
              [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
              CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
            FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
              FROM sys.all_objects) AS x
              WHERE Number <= LEN(@List)
              AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim)) = @Delim
          ) AS y
        );

Then, you can use it in a CROSS APPLY:

DECLARE @x TABLE(id INT, string VARCHAR(32));

INSERT @x VALUES(1,'34'),(2,'12{43{65{88{43{12{90{CD');

SELECT x.id, f.Value
  FROM @x AS x
  CROSS APPLY dbo.SplitString(x.string, '{') AS f;

Results:

ID      Value
----    -----
1       34
2       12
2       43
2       65
2       88
2       43
2       12
2       90
2       CD 

SQLfiddle demo

More on split functions (and better alternatives, if splitting strings coming from the application layer):

http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings

http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490