我在之前的回答中犯了一个错误,因为我给出的解决方案是针对 Oracle 数据库的。 OP 需要 sqlserver 的解决方案。
我已将我的代码翻译成 sql:
begin transaction
declare @good_id int
declare @bad_id int
declare @code varchar(128)
--update xxx as to change the lines containing ';' to just the number value. we do this by removing
--every character after ';' including ';'.
--we will use the updated values to calculate min and max over the id column
update XXX set code=SUBSTRING(code,1,CHARINDEX(';',code) - 1) where CHARINDEX(';',code)>0
--declare a cursor to calculate min (the good_id) and max (the bad_id) for a given code in table XXX
--this assumes the wrong id is always inserted secondly, i.e. it's value is always greater than the good id
declare myCursor cursor local fast_forward for
SELECT MIN (id) AS good_id, MAX (id) AS bad_id, code
FROM xxx
GROUP BY code
HAVING COUNT (1) = 2 --this condition is used to filter only duplicate entries, i.e only those entries in XXX that have the same code twice!
open myCursor
while 1=1 --while true
BEGIN
fetch next from myCursor into @good_id, @bad_id, @code --save the values obtained from the cursor in local variables
if @@FETCH_STATUS<>0 --when there is nothing left to fetch from the cursor we exit the while loop
begin
break
end
--update YYY with the correct values by using min/max(id) from the variables @good_id and @bad_id
update YYY set x_id=@good_id where x_id=@bad_id;
END --end while loop
close myCursor
deallocate myCursor
--delete the duplicates from XXX, i.e the bad entries represented by MAX
delete from XXX where id in(
select id from (
SELECT id,code,MAX (id) OVER (PARTITION BY code) as max_id FROM xxx) x where id=max_id)
commit transaction --save changes
在这组数据上测试了代码:
表 XXX
识别码
123 456
456 999
789 456;李
932 999;ab
表YYY
id x_id
111 789
222 123
333 000
444 932
555 456
运行后:
表 XXX
识别码
123 456
456 999
表YYY
id x_id
111 123
222 123
333 000
444 456
555 456
OP,如果它对你有用,请告诉我。如果您对代码有任何疑问,我很乐意回答。