连续序列号中断后的处理两种处理方法

本文介绍两种方法实现SQLServer中删除记录后,使编号连续的方法。一种是通过触发器,在删除记录时自动调整后续编号;另一种是使用存储过程手动处理编号更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**//*
*功能:中断ID的连续处理*
*适用:SQLServer2000/SQLServer2005*
*返回:NONE*
*作者:Flystone*
*日期:2008-05-13*
*/

--问题引入
/**//*
表﹕test
字段:u_nochar(2),
u_nameidchar(5)

---u_no-----------u_nameid-------
01A0001
02B8921
03F8762
.
99.....

比如我刪除了行66就是u_no為66的行,表紀錄成了:

---u_no-----------u_nameid-------
01A0001
02B8921
03F8762
.
65
67
.
99.....

我要讓u_no自己補齊刪除的數字﹐如下所示
---u_no-----------u_nameid-------
01A0001
02B8921
03F8762
.
.
.
65
66
.
98.....

*/

--环境准备



createtabletest(u_nochar(2),u_nameidchar(5))

insertintotestselect'01','A0001'unionselect
'02','B8921'unionselect
'03','F8762'unionselect
'04','C2345'unionselect
'05','C2345'unionselect
'06','C2345'unionselect
'07','C2345'unionselect
'08','C2345'unionselect
'09','C2345'
go
--方法一:触发器
createtriggertr_deleteid
ontest
fordelete
as
begin
declare@iint,@cint
select@I=min(cast(u_noasint)),@c=count(1)fromdeleted
updatetest
setu_no=right('00'+ltrim(cast(u_noasint)-@c),2)
whereu_no>@i
end
go
--原始记录
select*fromtest
/**//*

u_nou_nameid
------------
01A0001
02B8921
03F8762
04C2345
05C2345
06C2345
07C2345
08C2345
09C2345

(所影响的行数为9行)
*/

--单条删除
deletefromtestwhereu_no='02'
select*fromtest
/**//*
u_nou_nameid
------------
01A0001
02F8762
03C2345
04C2345
05C2345
06C2345
07C2345
08C2345

(所影响的行数为8行)
*/

--批量删除开始
deletefromtestwhereu_nobetween'02'and'04'
select*fromtest

/**//*

u_nou_nameid
------------
01A0001
02C2345
03C2345
04C2345
05C2345

(所影响的行数为5行)
*/


--方法二:过程处理
--
重新准备数据
droptabletest--一定要删除哦,因为上面的表有触发器哦
go

createtabletest(u_nochar(2),u_nameidchar(5))

insertintotestselect'01','A0001'unionselect
'02','B8921'unionselect
'03','C8762'unionselect
'04','D2345'unionselect
'05','E2345'unionselect
'06','F2345'unionselect
'07','G2345'unionselect
'08','H2345'unionselect
'09','I2345'
go


createprocproc_test
@u_novarchar(2),
@Lint
as
begin
declare@ichar(2)
set@i=right('00'+ltrim(cast(@u_noasint)+@L-1),2)

deletefromtestwhereu_nobetween@u_noand@i
updatetest
setu_no=right('00'+ltrim(cast(u_noasint)-@L),2)
whereu_no>@u_no
end
go

--原始记录
select*fromtest
/**//*

u_nou_nameid
------------
01A0001
02B8921
03F8762
04C2345
05C2345
06C2345
07C2345
08C2345
09C2345

(所影响的行数为9行)
*/

--单条删除
execproc_test'02',1
select*fromtest
go
/**//*

u_nou_nameid
------------
01A0001
02F8762
03C2345
04C2345
05C2345
06C2345
07C2345
08C2345

(所影响的行数为8行)
*/


--批量删除开始
execproc_test'02',2
select*fromtest
/**//*
u_nou_nameid
------------
01A0001
02E2345
03F2345
04G2345
05H2345
06I2345

(所影响的行数为6行)
*/

--清除环境
droptabletest
dropprocproc_test
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值