sql 複雜自動編號錯誤批量修改方案

 

[一籃飯特稀原創,轉載請註明出自http://www.cnblogs.com/wanghafan/p/5133953.html

 

前提:自動編號爲18位,前4位是年份,中間10位是XXXX,最後四位是0001-9999的自動編號。html

問題:某天發現2016年自動編號後四位從0001-0081後變爲7328-8530,出現編號錯亂問題(緣由未知待查)。但數據須要立刻批量重置,不然後續編號將繼續錯誤。sql

方案:截取2016年份的前14位拼接後4位正確自動編號。實現以下:spa

--查詢2016年我司項目編號,查看後四位是否正確
SELECT MyProjectNo,SUBSTRING(MyProjectNo,15,4) FROM dbo.ProjectT WHERE MyProjectNo LIKE '2016%' ORDER BY SUBSTRING(MyProjectNo,15,4)
--查詢正確編號
SELECT MyProjectNo AS '錯編號',SUBSTRING(MyProjectNo,15,4) AS '錯編號後四位',LEFT(MyProjectNo,14) AS '對編號前14位',
right('0000'+CAST(row_number() over (order by SUBSTRING(MyProjectNo,15,4))  AS VARCHAR(5)),4) AS '對編號後四位',
(LEFT(MyProjectNo,14)+right('0000'+CAST(row_number() over (order by SUBSTRING(MyProjectNo,15,4))  AS VARCHAR(5)),4)) AS '對編號'
FROM dbo.ProjectT 
WHERE MyProjectNo LIKE '2016%'
ORDER BY SUBSTRING(MyProjectNo,15,4)
--更新錯誤編號爲正確(批量腳本)
SELECT 'UPDATE dbo.ProjectT SET MyProjectNo='''+
(LEFT(MyProjectNo,14)+right('0000'+CAST(row_number() over (order by SUBSTRING(MyProjectNo,15,4))  AS VARCHAR(5)),4))
+''' WHERE MyProjectNo='''+MyProjectNo+''''
FROM dbo.ProjectT 
WHERE MyProjectNo LIKE '2016%'
ORDER BY SUBSTRING(MyProjectNo,15,4)

執行(批量腳本)實現數據重置。code

相關文章
相關標籤/搜索