在表中一系列的的纪录中,ID按照序列增长,如何找到空的ID呢?
[@more@]CREATE TABLE [t] (
[a] [tinyint] NOT NULL ,
[b] [varchar] (100)
) ON [PRIMARY]
GO
Insert into t (a,b) values ( 255, '255' );
Insert into t (a,b) values ( 1, '1' );
Insert into t (a,b) values ( 2, '2' );
Insert into t (a,b) values ( 4, '4' );
Insert into t (a,b) values ( 5, '5' );
Insert into t (a,b) values ( 8, '8' );
Insert into t (a,b) values ( 3, '3' );
用以下SQL可得到第一个空ID:
SELECT MIN(a) + 1 FROM t t1
WHERE NOT EXISTS(SELECT a FROM t WHERE a = t1.a + 1)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/66009/viewspace-866433/ ,如需转载,请注明出处,否则将追究法律责任。