sql语句 求最小可用Id

sql语句 求最小可用Id

select id+1 newtestid from test a where not exists (select 1 from test where id=a.id+1) order by id

使用说明:
1.先看where not exists,每条记录,都会进行 where id=a.id+1判断

2.where id=a.id+1 这个的判断结果,就是5,6,7,9,如果没有8,就会返回8

3.外面的A表 现在是1,里面就判断,有没有2,
外面的A表 现在是2,里面就判断,有没有3,
....
外面的A表 现在是7,里面没有8,返回8了

4.select 1就是返回一个1,表示存在

5. 使用案例:
1,2,3,4,5,6,7,8,9
有一天,老板把8这条记录删掉了,下次添加的时候,不想添加10,而想用回8这个记录

6.此sql语句的缺点:
如果序列中,1,2,3,4,5,6.... 老板把1删掉了,它是算不出1来的
原因:因为它用ID+1,1被删了的话,第一条就是2了,ID+1就去判断有没有3了

7.同理,如果序列中1,2,3,4,5,6,7,8,9,老板把前面的6个都删掉了,也求不出来

8.解决办法:解决的办法就是:另写一段代码,先判断有没有1这条记录,就OK了

建表以及添加数据、语句测试、删除前几项Id语句测试的sql脚本【sql server2000】

--创建test表
create table test
(
id int identity primary key nonclustered,
content varchar(50) not null default ''

)
go
--表创建结束
--添加数据
declare @i int
set @i=1
while @i<10
begin
set nocount on
insert into test(content) values(@i)
set @i=@i+1
end
--添加结束
--查询所有数据
select * from test
--删除第八条(随便删除一条)
delete from test where id=8
--测试求最小可用Id
select id+1 newtestid from test a where not exists (select 1 from test where id=a.id+1) order by id
--删除前两条数据
delete from test where id<=2
--重新测试
select id+1 newtestid from test a where not exists (select 1 from test where id=a.id+1)
--解决无法测试第一条是否已删除的办法
select top 1 id from test
--可以测试出第3条开始的 所以前2条是空的

转载自:http://hi.baidu.com/ykphp/blog/item/d84a6eb464ae67778bd4b21d.html

猜你喜欢

转载自sietmj.iteye.com/blog/1488324