刪除數(shù)據(jù)庫中重復(fù)數(shù)據(jù)的幾個(gè)方法
發(fā)布日期:2022-02-04 16:28 | 文章來源:腳本之家
declare@maxinteger,@idinteger
declarecur_rowscursorlocalforselect主字段,count(*)from表名groupby主字段havingcount(*)>1
opencur_rows
fetchcur_rowsinto@id,@max
while@@fetch_status=0
begin
select@max=@max-1
setrowcount@max
deletefrom表名where主字段=@id
fetchcur_rowsinto@id,@max
end
closecur_rows
setrowcount0
方法二
有兩個(gè)意義上的重復(fù)記錄,一是完全重復(fù)的記錄,也即所有字段均重復(fù)的記錄,二是部分關(guān)鍵字段重復(fù)的記錄,比如Name字段重復(fù),而其他字段不一定重復(fù)或都重復(fù)可以忽略。
1、對(duì)于第一種重復(fù),比較容易解決,使用selectdistinct*fromtableName就可以得到無重復(fù)記錄的結(jié)果集。
如果該表需要?jiǎng)h除重復(fù)的記錄(重復(fù)記錄保留1條),可以按以下方法刪除
selectdistinct*into#TmpfromtableName
droptabletableName
select*intotableNamefrom#Tmp
droptable#Tmp
發(fā)生這種重復(fù)的原因是表設(shè)計(jì)不周產(chǎn)生的,增加唯一索引列即可解決。
2、這類重復(fù)問題通常要求保留重復(fù)記錄中的第一條記錄,操作方法如下:
假設(shè)有重復(fù)的字段為Name,Address,要求得到這兩個(gè)字段唯一的結(jié)果集
selectidentity(int,1,1)asautoID,*into#TmpfromtableName
selectmin(autoID)asautoIDinto#Tmp2from#TmpgroupbyName,autoID
select*from#TmpwhereautoIDin(selectautoIDfrom#tmp2)
最后一個(gè)select即得到了Name,Address不重復(fù)的結(jié)果集(但多了一個(gè)autoID字段,實(shí)際寫時(shí)可以寫在select子句中省去此列)
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章