发现重复时,将字符附加到字符串

时间:2015-05-14 05:18:41

标签: sql-server sql-server-2012 duplicates

假设我有一个ID,名称和字段表来标记更新,如下所示:

+----+-------+---------+
| ID | Name  | Update? |
+----+-------+---------+
|  1 | A     | y       |
|  2 | B     | y       |
|  3 | xxB   |         |
|  4 | C     |         |
|  5 | D     | y       |
|  6 | xxD   |         |
|  7 | xxxD  |         |
|  8 | E     |         |
+----+-------+---------+

'update'是在名称后加一个'xx',但表中不能有重复的名称,所以我想在找到的任何重复项上附加一个'x'。因此,对于这一个,表格将更新为:

+----+-------+---------+
| ID | Name  | Update? |
+----+-------+---------+
|  1 | xxA   |         |
|  2 | xxB   |         |
|  3 | xxxB  |         |
|  4 | C     |         |
|  5 | xxD   |         |
|  6 | xxxD  |         |
|  7 | xxxxD |         |
|  8 | E     |         |
+----+-------+---------+

有关最佳方法的任何想法吗?它更新了我所坚持的初始更新时会出现的重复项,而且我不确定让它重新检查并更新所有重复级别是多么容易,例如A不重复, B为1级,D为2级等。

谢谢, 戴夫

1 个答案:

答案 0 :(得分:2)

试试这个:

SQL Fiddle

$('input[value="Moon"]').parent('td')

<强>结果

WITH CteUpdate AS(
    SELECT *, 
        base = REPLACE(Name, 'x', ''),
        xxName = REPLICATE('x', 
                    ROW_NUMBER() OVER(
                        PARTITION BY REPLACE(Name, 'x', '') 
                        ORDER BY ID
                    ) + 1
                ) + REPLACE(Name, 'x', '')
    FROM TestData
    WHERE
        REPLACE(Name, 'x', '') IN(
            SELECT Name FROM TestData WHERE [Update] = 1
        )
)
UPDATE CteUpdate 
    SET Name = xxName
        , [Update] = 0

首先,您希望获得具有相同基数ID Name Update ----------- ---------- ------ 1 xxA 0 2 xxB 0 3 xxxB 0 4 C 0 5 xxD 0 6 xxxD 0 7 xxxxD 0 8 E 0 Name减去Name s)的所有行与xx的行。要获得基础Update = 1,只需将Name替换为x

''

以上结果将是:

SELECT *, 
    base = REPLACE(Name, 'x', '')
FROM TestData
WHERE
    REPLACE(Name, 'x', '') IN(
        SELECT Name FROM TestData WHERE [Update] = 1
    )

然后,您想使用ID Name Update base ----------- ---------- ------ ------ 1 A 1 A 2 B 1 B 3 xxB 0 B 5 D 1 D 6 xxD 0 D 7 xxxD 0 D 。生成的ROW_NUMBER OVER(PARTITION BY base ORDER BY ID)将是ROW_NUMBER + 1

上要添加的x的数量
base

上述查询的结果将是:

WITH CteUpdate AS(
    SELECT *, 
        base = CAST(REPLACE(Name, 'x', '') AS VARCHAR(1))
    FROM TestData
    WHERE
        REPLACE(Name, 'x', '') IN(
            SELECT Name FROM TestData WHERE [Update] = 1
        )
)
SELECT
    RN = ROW_NUMBER() OVER(PARTITION BY base ORDER BY ID),
    xxName = REPLICATE('x', ROW_NUMBER() OVER(PARTITION BY base ORDER BY ID) + 1) + base
FROM CteUpdate

ID Name Update base RN xxName ----------- ---------- ------ ------ ----- --------- 1 A 1 A 1 xxA 2 B 1 B 1 xxB 3 xxB 0 B 2 xxxB 5 D 1 D 1 xxD 6 xxD 0 D 2 xxxD 7 xxxD 0 D 3 xxxxD 现在将更新为xxName