Sql server 第一次出现重复的SQL更新
我有一个数据库,它是由一个实用程序填充的,该实用程序不能很好地处理同时请求 在这些表中插入行的逻辑存在缺陷,从而允许在派生表中重复。我的目标是修复这些副本 出现了两种类型的重复项:Sql server 第一次出现重复的SQL更新,sql-server,sql-update,duplicates,Sql Server,Sql Update,Duplicates,我有一个数据库,它是由一个实用程序填充的,该实用程序不能很好地处理同时请求 在这些表中插入行的逻辑存在缺陷,从而允许在派生表中重复。我的目标是修复这些副本 出现了两种类型的重复项: 钥匙是重复的,但我们可以用号码告诉他们 分开 其中键和数字都是重复的,在本例中为I 要更新第一个事件 情况是这样的 /** Sequence of events **/ /** First Set (Correct) **/ Insert into Base values(100,'Base1'); /
/** Sequence of events **/
/** First Set (Correct) **/
Insert into Base values(100,'Base1');
/** Find the biggest IKey in Base Table **/
/** Set that as IKey in Derived Table (IKey = 1)**/
Insert into Derived values(1,100,'Derived1');
Insert into Base values(101,'Base2');
/** Find the biggest IKey in Base Table **/
/** Set that as IKey in Derived Table (IKey = 2)**/
Insert into Derived values(2,101,'Derived2');
/** Second Set ( duplicate IKey )**/
Insert into Base values(200,'Base3');
/** Find the biggest IKey in Base Table **/
/** We would have gotten 3, but there was another insert before this query could be run **/
Insert into Base values(201,'Base4');
/** Because of the insert, we got a 4 instead of a 3 **/
/** Set that as IKey in Derived Table (IKey = 4)**/
Insert into Derived values(4,200,'Derived3');
/** Find the biggest IKey in Base Table **/
/** Set that as IKey in Derived Table (IKey = 4)**/
Insert into Derived values(4,201,'Derived4');
/** Third Set ( duplicate IKey and Number )**/
Insert into Base values(300,'Base5');
/** Find the biggest IKey in Base Table **/
/** We would have gotten 5, but there was another insert before this query could be run **/
/** This even had the "Number" column same as previous insert **/
Insert into Base values(300,'Base6');
/** Because of the insert, we got a 6 instead of a 5 **/
/** Set that as IKey in Derived Table (IKey = 6)**/
Insert into Derived values(6,300,'Derived5');
/** Find the biggest IKey in Base Table **/
/** Set that as IKey in Derived Table (IKey = 6)**/
Insert into Derived values(6,300,'Derived6');
结果如下表所示:
基地
衍生
IKey Number Derived
1 100 Derived1
2 101 Derived2
4 200 Derived3
4 201 Derived4
6 300 Derived5
6 300 Derived6
我已经找到了这个案件的解决办法
我想为#2找到一个解决方案
这里是一个工作区,用来试验这个问题。
如果您使用
行数()分区方式()
函数,那么您将获得“组”(相同标识符)的编号;然后,您可以使用每个组的第2行更新第1行。如果您使用row#u number()分区by()
函数,则可以获得“组”的编号(相同标识符);然后,您可以使用每个组的行2更新行1,每个组的行可能重复
IKey Number Derived
1 100 Derived1
2 101 Derived2
4 200 Derived3
4 201 Derived4
6 300 Derived5
6 300 Derived6
UPDATE Derived
Set Derived.IKey = Derived.IKey - 1
FROM Derived
INNER JOIN
Base
ON
Derived.IKey - 1 = Base.IKey
AND
Derived.Number = Base.Number
WHERE Derived.IKey
IN
(
/** Query to get all records which have duplicates in a table but the previous key is not used**/
SELECT
Derived.IKey
FROM
Derived
WHERE
Derived.IKey - 1 NOT IN (SELECT IKey FROM Derived)
GROUP BY
Derived.IKey
HAVING
COUNT(Derived.IKey) > 1
)