⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 -补位法.sql

📁 sqlserver 数据库编程的绝好脚本
💻 SQL
字号:
--自已做标识列的例子,不自动重排编号,而是自动补号:

--创建得到最大id的函数
create function f_getid()
returns char(3)
as
begin
declare @id int

if not exists(select 1 from tb where id='001')
	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(right('000'+cast(@id as varchar),3))
end
go

--创建表
create table tb(id char(3) 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

--删除部分记录
delete from tb where name in('张三','张七','张八','张十')

--显示删除后的结果
select * from tb

--再次插入记录
insert into tb(name) values('李一')
insert into tb(name) values('李二')

--显示插入的结果
select * from tb order by id
go

--删除环境
drop table tb
drop function f_getid

/*--测试结果
id   name       
---- ---------- 
001  李一
002  张四
003  张五
004  张六
005  李二
007  张九

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

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -