SQL Server脚本快速使用递增整数替换所有找到的字符串

时间:2015-11-27 08:47:37

标签: sql-server

我有大INSERT个SQL脚本,我希望通过快速替换来修改它。通过用interger替换每个找到的字符串,其中每个下一个整数都是前一个整数+ 1。

在:

INSERT Compartment (CompartmentID) VALUES ('A')
INSERT Compartment (CompartmentID) VALUES ('B')

之后:

INSERT Compartment (CompartmentID) VALUES (1)
INSERT Compartment (CompartmentID) VALUES (2)

我知道如何找到特定字符串,但我找不到任何语法或方法必须替换它递增整数。

2 个答案:

答案 0 :(得分:2)

您可以将所有char charartmentID替换为如下所示的有序数字:

declare @Compartment table(CompartmentID varchar(10), name varchar(10), intID int)
INSERT INTO @Compartment(CompartmentID, name) values
    ('a', 'a')
    , ('b', 'b')
    , ('c', 'c')
    , ('d', 'd')
    , ('e', 'e')

UPDATE c SET CompartmentID = o.ID
FROM @Compartment c
INNER JOIN (
    SELECT CompartmentID, ID = ROW_NUMBER() over(ORDER BY CompartmentID) 
    FROM @Compartment
) o ON c.CompartmentID = o.CompartmentID

SELECT * FROM @Compartment

输出

CompartmentID   name
1               a
2               b
3               c
4               d
5               e

最好创建一个int类型的新列,或者在更新完成后更改CompartmentID的类型。

如果您希望自动增加数字,还应使用标识列。

答案 1 :(得分:1)

不确定如何处理空字符串。您可以选择CompartmentID包含不是数字的字符的行,并像这样更新结果集:

List<string>

结果:

DECLARE @Compartment table(CompartmentID varchar(20))
INSERT @Compartment(CompartmentID) VALUES ('A'),('A'),('B'),('1'),('A1')


-- EDIT: Changed answer

;WITH CTE as
(
  SELECT CompartmentID, DENSE_RANK() over (ORDER BY CompartmentID) rn
  FROM @Compartment
  --WHERE CompartmentID LIKE '%[^0-9]%' OR CompartmentID = ''
)
UPDATE CTE
SET CompartmentID = rn
FROM CTE

注意:现在所有ID都会更改CompartmentID(也就是数字CompartmentID),旧CompartmentID的相同值将获得相同的数值。