简化列中的值

时间:2017-09-19 14:48:30

标签: sql sql-server tsql sql-server-2012

我的表看起来像这样:

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

我想更新表格,所以看起来像这样:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您可以使用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);

修改

  

我的表有600个条目,我想要较小的数字

没有前导零

不会导致零: Rextester Demo

答案 1 :(得分:0)

当数字总是在正确的位置时,这很容易。为了好玩,这里有你如何'为以下示例数据解决此问题:

示例数据

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