基于sql server中的数字拆分字符串

时间:2013-01-02 18:28:22

标签: sql-server string split numbers

在sql Server中,我需要根据数字拆分字符串。什么是最好的方式。 例如,我需要拆分字符串

  1. 我正在寻找此查询。你能帮忙吗?我真的很感激。
  2. 我要找的结果是

    1. 我正在寻找这个答案。
    2. 能帮忙吗?
    3. 我真的很感激。
    4. 感谢。

2 个答案:

答案 0 :(得分:2)

快速又脏,但它有效。如果您愿意,可以充分利用优化空间

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;

答案 1 :(得分:1)

我建议您使用Jeff Moden的优秀“CSV Splitter”,可以在http://www.sqlservercentral.com/articles/Tally+Table/72993/找到。 Jeff已经通过SQL Server社区的一些良好反馈真正优化了这种操作。