--自已做標識列的例子,不自動重排編號,而是自動補號:
--創建得到最大id的函數
IF NOT OBJECT_ID('[f_getid]') IS NULL
DROP function f_getid
GO
create function f_getid()
returns int
as
begin
declare @id int
if not exists(select 1 from tb where id=1)
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
end
lb_re:
return @id
end
go
--創建表
IF NOT OBJECT_ID('[tb]') IS NULL
DROP TABLE tb
GO
create table tb(id int 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
/*
id name
----------- ----------
1 張三
2 張四
3 張五
4 張六
5 張七
6 張八
7 張九
8 張十
(8 行受影響)
*/
--刪除部分記錄
delete from tb where name in('張三','張七','張八','張十')
--顯示刪除後的結果
select * from tb
/*
id name
----------- ----------
2 張四
3 張五
4 張六
7 張九
(4 行受影響)
*/
--再次插入記錄
insert into tb(name) values('李一')
insert into tb(name) values('李二')
--顯示插入的結果
select * from tb order by id
/*
id name
----------- ----------
1 李一
2 張四
3 張五
4 張六
5 李二
7 張九
(6 行受影響)
*/
--刪除環境
drop table tb
drop function f_getid
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/htl258/archive/2009/07/22/4369943.aspx