发现删除其中一个后,后面的ID都不会自动减一,还是保持原来的ID.
这种情况应该怎么处理啊?

解决方案 »

  1.   

    这样比较好,自增的int一般够用了,也可以用bigint--自已做标识列的例子,不自动重排编号,而是自动补号:--创建得到最大id的函数
    create function f_getid()
    returns char(3)
    as
    begin
    declare @id intif not exists(select 1 from tb where id='001')
    set @id=1
    else
    begin
    select @id=max(id) from tb
    if @id is null
    set @id=1
    else
    begin
    declare @id1 int
    select @id1=min(id) from tb a where id<>@id and not exists(select 1 from tb where id=a.id+1)
    if @id1 is not null set @id=@id1
    set @id=@id+1
    end
    endlb_re:
    return(right('000'+cast(@id as varchar),3))
    end
    go--创建表
    create table tb(id char(3) primary key default dbo.f_getid(),name varchar(10))
    go
    --插入记录测试
    insert into tb(name) values('张三')
    insert into tb(name) values('张四')
    insert into tb(name) values('张五')
    insert into tb(name) values('张六')
    insert into tb(name) values('张七')
    insert into tb(name) values('张八')
    insert into tb(name) values('张九')
    insert into tb(name) values('张十')--显示插入的结果
    select * from tb--删除部分记录
    delete from tb where name in('张三','张七','张八','张十')--显示删除后的结果
    select * from tb--再次插入记录
    insert into tb(name) values('李一')
    insert into tb(name) values('李二')--显示插入的结果
    select * from tb order by id
    go--删除环境
    drop table tb
    drop function f_getid/*--测试结果
    id   name       
    ---- ---------- 
    001  李一
    002  张四
    003  张五
    004  张六
    005  李二
    007  张九(所影响的行数为 6 行)
    --*/
      

  2.   

    完全没有必要减1。自增列属性设置成bigint够用的。我们系统都是bigint的的。
      

  3.   

    select *,[No]=(select count(*) from tb where id>=t.id) from tb t
      

  4.   

    把自动编号属性去掉->保存,再改成自动编号->保存,就行了。
      

  5.   

    被CSDN乐于助人的人们感动了。
    虽然我现在还是个菜鸟,但是我成长起来以后一定会像大家一样多帮助刚起步的。