代码之家  ›  专栏  ›  技术社区  ›  user8001246

简化列中的值

  •  1
  • user8001246  · 技术社区  · 9 年前

    我的桌子看起来像这样:

    |    col1     | col2    | col3    |
    | xxx001xxx1  | ...     | ...     |
    | xxx001xxx2  | ...     | ...     |
    | xxx001xxx3  | ...     | ...     |
    | xxx002xxx1  | ...     | ...     |
    | xxx002xxx2  | ...     | ...     |
    | xxx003xxx1  | ...     | ...     |
    

    我想更新表,因此它将如下所示:

    |    col1     | col2    | col3    |
    |     1       | ...     | ...     |
    |     1       | ...     | ...     |
    |     1       | ...     | ...     |
    |     2       | ...     | ...     |
    |     2       | ...     | ...     |
    |     3       | ...     | ...     |
    

    2 回复  |  直到 9 年前
        1
  •  3
  •   Lukasz Szozda    9 年前

    你可以用 SUBSTRING :

    SELECT CAST(SUBSTRING(col1, 4,3) AS INT) AS col1, col2, col3
    FROM tab_name;
    

    UPDATE

    UPDATE tab_name
    SET col1 = CAST(SUBSTRING(col1, 4,3) AS INT);
    

    不会有前导零: Rextester Demo

        2
  •  0
  •   Alan Burstein    9 年前

    当数字总是在正确的位置时,这是相当容易的。有趣的是,下面是如何解决以下示例数据的问题:

    col1
    --------------
    xxx001xxx1
    xxxx005xxx2
    xxxxxx0010xxx3
    xxx00015xxx1
    xxx00007xxx2
    xxx0033xxx1
    

    -- sample data
    declare @sometable table (col1 varchar(100));
    insert @sometable
    values ('xxx001xxx1'), ('xxxx005xxx2'), ('xxxxxx0010xxx3'), 
           ('xxx00015xxx1'), ('xxx00007xxx2'), ('xxx0033xxx1');
    
    -- solution
    with prep as ( select col1, nbrStart = substring(col1, patindex('%[0-9][0-9]%',col1), 100)
                   from @sometable)
    select col1,
           nbr = cast(substring(nbrStart, 1, patindex('%[^0-9]%', nbrStart)-1) as int)
    from prep;
    

    后果

    col1                               nbr
    ---------------------------------- -----------
    xxx001xxx1                         1
    xxxx005xxx2                        5
    xxxxxx0010xxx3                     10
    xxx00015xxx1                       15
    xxx00007xxx2                       7
    xxx0033xxx1                        33