--自已做标识列的例子:--创建得到最大id的函数
create function f_getid()
returns int
as
begin
declare @id int
select @id=max(id) from tb
set @id=isnull(@id,0)+1
return(@id)
end
go--创建表
create table tb(id int default dbo.f_getid() primary key,name varchar(10))
go--创建触发器,在删除表中的记录时,自动更新记录的id
create trigger t_delete on tb
AFTER delete
as
declare @id int,@mid int
select @mid=min(id),@id=@mid-1 from deleted
update tb set id=@id,@id=@id+1 where id>@mid
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--删除环境
drop table tb
drop function f_getid

解决方案 »

  1.   

    --id不能用标识列.创建一个触发器就行了.--创建触发器,重排id
    create trigger t_del on B
    after delete
    as
    update B set id=(select sum(1) from B where id<=a.id and a_id=a.a_id)
    from B a
    go
      

  2.   

    --下面是数据测试--创建表(因为不会用到A表,所以忽略它)
    create table B(id int,a_id int,tel varchar(10))
    insert into B
    select 1,1,'1111'
    union all select 2,1,'2222'
    union all select 3,1,'3333'
    union all select 1,2,'4444'
    union all select 2,3,'5555'go
    --创建触发器,重排id
    create trigger t_del on B
    after delete
    as
    update B set id=(select sum(1) from B where id<=a.id and a_id=a.a_id)
    from B a
    go--删除数据
    delete from B where id=3 and a_id=1--显示结果
    select * from Bgo
    --删除测试环境
    drop table b/*--测试结果
    id          a_id        tel        
    ----------- ----------- ---------- 
    1           1           1111
    2           1           2222
    1           2           4444
    1           3           5555(所影响的行数为 4 行)
    --*/
      

  3.   

    请问下
    创建一个这样的函数
    create function f_getid()
    returns int
    as
    begin
    declare @id int
    select @id=max(id) from tb
    set @id=isnull(@id,0)+1
    return(@id)
    endselect @id=max(id) from tb这样会影响速度啊