日期:2014-05-19  浏览次数:20549 次

请教一个简单的脚本,,有关快速找出中断序号的问题
a表:
列名:SerialNo,memo
类型:数字型,文本型
数据:1001         ,aaa
            1002         ,bbb
            1003         ,ccc
            1006         ,ddd
            1007         ,eee
            ...
            5500001   ,ttt
            ...
            9999999   ,yyy

问题,如何用一个脚本最快速的在上述高达百万的数据中,快速找出中断的数字,
即上述中断的:1004、1005等


非常感谢,解决的话立即高分赠送



------解决方案--------------------
declare @maxid int
select @maxid=max(noid) from tblA
set rowcount @maxid
select id=identity(bigint,1001,1) into #t from sysobjects a,sysobjects b,sysobjects c select id from #t a left join tblA b on a.id=b.SerialNo
where b.SerialNo is null

drop table #t
------解决方案--------------------
select
rtrim(m.num)+ '-- '+rtrim(min(n.num)) as 断号区间
from
(select t.SerialNo+1 as num
from a t
where not exists(select 1 from a where SerialNo=t.SerialNo+1)) m,
(select t.SerialNo-1 as num
from a t
where not exists(select 1 from a where SerialNo=t.SerialNo-1)) n
where
m.num <=n.num
group by
m.num
------解决方案--------------------
记录编号缺号的处理
编号 姓名
1 张山
3 历史
4 王无
6 李强
桥三
大兵

我想对没有编号的进行编号的自动处理,但是已经有编号的不要进行修改。
如果发现有断号的就将号码分配给没有编号的。
结果如下:
编号 姓名
1 张山
3 历史
4 王无
6 李强
2 桥三
5 大兵


遍历记录,如果id为空,则找出最小未使用id,然后update

找最小未使用id如下:
select (case when exists (select 1 from test where id=1)
then min(id+1) else 1 end)
from test
where id not in(select id-1 from test)


CREATE TABLE [bhb] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[bh] [int] NULL
) ON [PRIMARY]

Declare @intI int
Set @intI = 1
Declare @intChdI int
While @intI < 500 --根据实际需要来确定循环次数
Begin
if not EXISTS(select bh from twhere bh=@intI)
begin
Insert Into bhb(bh) Values (@intI)
end
Set @intI= @intI + 1
End
*/

Declare @intI int
set @intI=1
update t set bh=(select bh from bhb where id=@intI),@intI=@intI+1 where bh is null

drop table bhb


while exists (select 1 from tablename where 编号 is null)
begin
set rowcount 1
update tablename
set 编号=(select min(编号)+1 from tablename a where 编号 is not null
and not exists (select 1 from tablename where 编号=a.编号+1)
)
where 编号 is null
set rowcount 0
end

--检查结果
select * from tablename
order by 编号


---------------------------
题目:
现在数据库由于需要要自己定义唯一编号,唯一编号由3个数字组成。这三个数字我存储为nvarchar.
由于唯一编号在使用中不可能超过999条记录,所以3个足够用。

但是碰到一个问题.第一次使用时添加记录可以001,002,003...这样顺序添加.
当对这些记录进行删除之后再次添加.要核对输入的记录是否重复。这样非常被动。
每次添加记录都要验证该编号是否存在。设计这样的数据库,实在是没辙.
现在有没有办法能够自己得出一个在999内的未使用的编号呢。
非常感谢。用存储过程亦可。我有想过遍历,但是效率不高。希望有更简洁的方式。


--1、没有数据的情况
if object_id( 'pubs..t ') is not null
drop table t