【问题标题】:Splitting a String into rows将字符串拆分为行
【发布时间】:2011-03-18 13:21:08
【问题描述】:

我有一个表格,其中包含由“+”分隔的多个字符串组成的字段。

字符串的每个部分的长度为 2 或 3 个字符。示例:'ab+cde+fg'

每行有 1 到 3 个部分(因此有些行不需要拆分)。上面的示例应该返回 3 行:'ab''cd''fg'

我已经在 Internet 上搜索了存储过程,但似乎没有一个适合我的特定需求。我自己没有编写这样的程序的 SQL 技能。

【问题讨论】:

    标签: sql string split advantage-database-server


    【解决方案1】:

    一般算法是这样工作的:

    DECLARE input CHAR(100);
    DECLARE separator_position INTEGER;
    
    SET input = 'AA+CCC+D';
    
    CREATE TABLE
       #output
    (
       part CHAR(10)
    );
    
    SET separator_position = POSITION('+' IN input);
    
    WHILE separator_position > 0 DO
    
      INSERT INTO #output (part) VALUES (SUBSTRING(input, 1, separator_position - 1));
      SET input = SUBSTRING(input, separator_position + 1, 100); 
    
      SET separator_position = POSITION('+' IN input);
    END WHILE;
    
    INSERT INTO #output(part) VALUES (SUBSTRING(input, 1, 10));
    
    SELECT * FROM #output;
    

    这段代码将在临时表#output中插入3行AACCCD

    这是一个使用多字符分隔符的版本,还包含一个部分计数器:

    DECLARE @input STRING;
    DECLARE @delimiter_position INTEGER;
    DECLARE @delimiter STRING;
    
    TRY DROP TABLE #output; CATCH ALL END TRY;
    
    SET @delimiter = CHAR(13) + CHAR(10);
    SET @input = 'AA' + CHAR(13) + CHAR(10) + 'CCC' + CHAR(13) + CHAR(10) + 'D';
    
    CREATE TABLE
       #output
    (
         counter AUTOINC
       , part CHAR(10)
    );
    
    SET @delimiter_position = POSITION(@delimiter IN @input);
    
    WHILE @delimiter_position > 0 DO
    
      INSERT INTO #output (part) VALUES (LEFT(@input, @delimiter_position - 1));
      SET @input = RIGHT(@input, LENGTH(@input) - (@delimiter_position + LENGTH(@delimiter)) + 1); 
    
      SET @delimiter_position = POSITION(@delimiter IN @input);
    END WHILE;
    
    INSERT INTO #output(part) VALUES (LEFT(@input, LENGTH(@input)));
    
    SELECT * FROM #output;
    

    【讨论】:

    • 完美运行!非常感谢您的宝贵时间
    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多