/*
测试环境:windows 2K server + Mssql 2000
所有功能都进行测试过,并有相应的结果集,如果有什么疑义在论坛跟帖
关于版权的说明:部分资料来自互联网,如有不当请联系版主,版主会在第一时间处理。
功能:自已做标识列的例子,解决了本身数据库自增列在删除后ID不连贯的情况,但是对一个数据量大的表,参照者得注意速度哟。
*/
--创建得到最大id的函数
create function f_getmaxid()
returns int
as
begin
declare @maxid int
select @maxid=max(id)
from test_tb
set @maxid=isnull(@maxid,0)+1
return(@maxid)
end
go
--创建表
create table test_tb(id int default dbo.f_getmaxid(),[name] varchar(10))
go
--创建触发器,在删除表中的记录时,自动更新记录的id
create trigger tr_delete on test_tb
AFTER delete
as
declare @id int,@mid int
select @mid=min(id),@id=@mid-1
from deleted
update test_tb
set id=@id,@id=@id+1
where id>@mid
go
--插入记录测试
insert into test_tb(name) values('张三')
insert into test_tb(name) values('张四')
insert into test_tb(name) values('张五')
insert into test_tb(name) values('张六')
insert into test_tb(name) values('张七')
insert into test_tb(name) values('张八')
insert into test_tb(name) values('张九')
insert into test_tb(name) values('张十')
--显示插入的结果
select * from test_tb
/*
id name
----------- ----------
1 张三
2 张四
3 张五
4 张六
5 张七
6 张八
7 张九
8 张十
(所影响的行数为 8 行)
*/
--删除部分记录
delete from test_tb where name in('张四','张三','张八','张十')
--显示删除后的结果
select * from test_tb
/*
id name
----------- ----------
1 张五
2 张六
3 张七
4 张九
(所影响的行数为 4 行)
*/
--清理环境
drop table test_tb
drop function f_getmaxid