嘗試這一個:
SQL Fiddle
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
首先,你想有與Update = 1
這些行相同的基本Name
(該Name
減去xx
S)的所有行。爲了獲得基礎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
將要對所述查詢的所述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
結果加入x
S中的數目將是:
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
現在將更新的Name
。
當你想要A到XXA然後E也是XXE時,你確切地想要什麼......但是你已經提到過E – mohan111