在很多的時候,我們會在數(shù)據(jù)庫的表中設(shè)置一個字段:ID,這個ID是一個IDENTITY,也就是說這是一個自增ID。當(dāng)并發(fā)量很大并且這個字段不是主鍵的時候,就有可能會讓這個值重復(fù);或者在某些情況(例如插入數(shù)據(jù)的時候出錯,或者是用戶使用了Delete刪除了記錄)下會讓ID值不是連續(xù)的,比如1,2,3,5,6,7,10,那么在中間就斷了幾個數(shù)據(jù),那么我們希望能在數(shù)據(jù)中找出這些相關(guān)的記錄,我希望找出的記錄是3,5,7,10,通過這些記錄可以查看這些記錄的規(guī)律來分析或者統(tǒng)計;又或者我需要知道那些ID值是沒有的:4,8,9。
解決辦法的核心思想是:獲取到當(dāng)前記錄的下一條記錄的ID值,再判斷這兩個ID值是否差值為1,如果不為1那就表示數(shù)據(jù)不連續(xù)了。
執(zhí)行下面的語句生成測試表和測試記錄 --生成測試數(shù)據(jù)
if exists (select * from sysobjects where id = OBJECT_ID('[t_IDNotContinuous]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [t_IDNotContinuous]
CREATE TABLE [t_IDNotContinuous] (
[ID] [int] IDENTITY (1, 1) NOT NULL,
[ValuesString] [nchar] (10) NULL)
SET IDENTITY_INSERT [t_IDNotContinuous] ON
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 1,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 2,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 3,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 5,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 6,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 7,'test')
INSERT [t_IDNotContinuous] ([ID],[ValuesString]) VALUES ( 10,'test')
SET IDENTITY_INSERT [t_IDNotContinuous] OFF
select * from [t_IDNotContinuous]
(圖1:測試表) --拿到當(dāng)前記錄的下一個記錄進(jìn)行連接
select ID,new_ID
into [t_IDNotContinuous_temp]
from (
select ID,new_ID = (
select top 1 ID from [t_IDNotContinuous]
where ID=(select min(ID) from [t_IDNotContinuous] where ID>a.ID)
)
from [t_IDNotContinuous] as a
) as b
select * from [t_IDNotContinuous_temp]
(圖2:錯位記錄) --不連續(xù)的前前后后記錄
select *
from [t_IDNotContinuous_temp]
where ID <> new_ID - 1
--查詢原始記錄
select a.* from [t_IDNotContinuous] as a
inner join (select *
from [t_IDNotContinuous_temp]
where ID <> new_ID - 1) as b
on a.ID >= b.ID and a.ID <=b.new_ID
order by a.ID