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

/**/ /*
*功能:中断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.....

*/

-- 环境准备



create table test(u_no char ( 2 ),u_nameid char ( 5 ))

insert into test select ' 01 ' , ' A0001 ' union select
' 02 ' , ' B8921 ' union select
' 03 ' , ' F8762 ' union select
' 04 ' , ' C2345 ' union select
' 05 ' , ' C2345 ' union select
' 06 ' , ' C2345 ' union select
' 07 ' , ' C2345 ' union select
' 08 ' , ' C2345 ' union select
' 09 ' , ' C2345 '
go
-- 方法一:触发器
create trigger tr_deleteid
on test
for delete
as
begin
declare @i int , @c int
select @I = min ( cast (u_no as int )), @c = count ( 1 ) from deleted
update test
set u_no = right ( ' 00 ' + ltrim ( cast (u_no as int ) - @c ), 2 )
where u_no > @i
end
go
-- 原始记录
select * from test
/**/ /*

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

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

-- 单条删除
delete from test where u_no = ' 02 '
select * from test
/**/ /*
u_nou_nameid
------------
01A0001
02F8762
03C2345
04C2345
05C2345
06C2345
07C2345
08C2345

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

-- 批量删除开始
delete from test where u_no between ' 02 ' and ' 04 '
select * from test

/**/ /*

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

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


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

create table test(u_no char ( 2 ),u_nameid char ( 5 ))

insert into test select ' 01 ' , ' A0001 ' union select
' 02 ' , ' B8921 ' union select
' 03 ' , ' C8762 ' union select
' 04 ' , ' D2345 ' union select
' 05 ' , ' E2345 ' union select
' 06 ' , ' F2345 ' union select
' 07 ' , ' G2345 ' union select
' 08 ' , ' H2345 ' union select
' 09 ' , ' I2345 '
go


create proc proc_test
@u_no varchar ( 2 ),
@L int
as
begin
declare @i char ( 2 )
set @i = right ( ' 00 ' + ltrim ( cast ( @u_no as int ) + @L - 1 ), 2 )

delete from test where u_no between @u_no and @i
update test
set u_no = right ( ' 00 ' + ltrim ( cast (u_no as int ) - @L ), 2 )
where u_no > @u_no
end
go

-- 原始记录
select * from test
/**/ /*

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

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

-- 单条删除
exec proc_test ' 02 ' , 1
select * from test
go
/**/ /*

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

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


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

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

-- 清除环境
drop table test
drop proc proc_test

你可能感兴趣的:(C++,c,C#,Go)