1

In sql Server, I need to split a string based on number. What would be the best way for that. For example, I need to split below string

  1. I am looking for this query. 2. Can you please help. 3. I would really appreciate that.

the result I am looking for is

  1. I am looking for this answer.
  2. Can you please help.
  3. I would really appreciate that.

Thanks.

2
  • what version of sql server? Commented Jan 2, 2013 at 19:08
  • In the past I have written a C# applications for similar need but I'm not sure if that is an option for you or not. Commented Jan 2, 2013 at 19:36

2 Answers 2

2

Quick and dirty, but it works. Plenty of room for optimizing if you wish

DECLARE @str AS VARCHAR(MAX);
SET @str = '1. I am looking for this query. 2. Can you please help. 3. I would really appreciate that.';

DECLARE @counter INT;
DECLARE @table TABLE ([Text] VARCHAR(MAX));
DECLARE @currentPattern VARCHAR(5);
DECLARE @nextPattern VARCHAR(5);

SET @counter = 1;
WHILE 1=1
BEGIN
    -- Set the current and next pattern to look for (ex. "1. ", "2. ", etc.)
    SET @currentPattern = '%' + CAST(@counter AS VARCHAR(4)) + '. %';
    SET @nextPattern = '%' + CAST(@counter + 1 AS VARCHAR(4)) + '. %';

    -- Check if the current pattern exists.
    IF (SELECT PATINDEX(@currentPattern, @str)) > 0
    BEGIN
        -- Check if the next pattern exists.
        IF (SELECT PATINDEX(@nextPattern, @str)) > 0
        BEGIN
            -- There is another pattern, so only get the text for the current one.
            INSERT INTO @table VALUES (SUBSTRING(@str, 1, PATINDEX(@nextPattern, @str) - 1));
            SET @str = SUBSTRING(@str, PATINDEX(@nextPattern, @str), LEN(@str) - PATINDEX(@nextPattern, @str) + 1);
        END
        ELSE
        BEGIN
            -- No other patterns exist, so just insert the variable text.
            INSERT INTO @table VALUES (@str);
        END
    END
    ELSE
    BEGIN
        -- Current pattern does not exist; break out of loop.
        BREAK;
    END

    SET @counter = @counter + 1;
END
SELECT * FROM @table;
Sign up to request clarification or add additional context in comments.

Comments

1

I'd recommend that you use Jeff Moden's excellent "CSV Splitter", which can be found at http://www.sqlservercentral.com/articles/Tally+Table/72993/. Jeff has really optimized this kind of operation with some good feedback from the SQL Server community.

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.