0

The below Split function works well. But it changes the order of my input. Please help me to get desired output.

With respect to http://www.codeproject.com/Tips/85943/Split-function.

Input

SELECT * from dbo.fnStringSplitter('1,3,2', ',')

Expected Output

1
3
2

NOT

1
2
3
4
  • why is your expected output 1, 3, 2? Commented Jan 29, 2016 at 16:48
  • You pass 1,2,3 and you want 1,3,2. I guess you are changing the order not split string function Commented Jan 29, 2016 at 16:48
  • Edited by Question. Please work and getback. It is reasonable Question only Commented Jan 29, 2016 at 16:51
  • That is actually the worst performing splitter you can find. A loop is horribly inefficient for this type of thing. Check out this article for much better splitters. sqlperformance.com/2012/07/t-sql-queries/split-strings Commented Jan 29, 2016 at 16:54

2 Answers 2

1

You need to use Order by to get the result in required Order try changing the Split string function like this

Try this way

CREATE FUNCTION dbo.Fnstringsplitter (@string    NVARCHAR(MAX),
                                      @delimiter VARCHAR(2))
RETURNS @result TABLE(
  id        INT IDENTITY(1, 1),
  split_val NVARCHAR(MAX))
  BEGIN
      DECLARE @start INT,
              @end   INT

      SELECT @start = 1,
             @end = Charindex(@delimiter, @string)

      WHILE @start < Len(@string) + 1
        BEGIN
            IF @end = 0
              SET @end = Len(@string) + 1

            INSERT INTO @result
                        (split_val)
            VALUES      (Substring(@string, @start, @end - @start))

            SET @start = @end + 1
            SET @end = Charindex(@delimiter, @string, @start)
        END

      RETURN
  END 

Query:

SELECT split_val
FROM   dbo.Fnstringsplitter('1,3,2', ',')
ORDER  BY id 

Note: This is not a efficient way to split the data. But reliable in your case

Sign up to request clarification or add additional context in comments.

3 Comments

This seems good. I will test and mark it as answered. I need as function. you have hardcorded. Give it as function
@jamir - Updated check now
need one more help. check Question i have asked in stackoverflow.com/questions/35102631/…
0

Datasets within SQL are inherently unordered. When you require an explicit order you must explicitly request/create it. This can be done using the ORDER BY clause or via code in your front end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.