j9988 按日期生成自增号!

博客主要围绕数据库操作展开,使用Go语言创建了num_tb和tb表,为tb表创建了聚集索引和触发器。触发器用于在插入数据时更新num_tb表的记录,并对插入的id进行处理。最后进行了插入记录测试,插入大量数据后删除了tb表。

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

create table num_tb(d datetime,id int)
insert num_tb select '2004-01-01',1

create table tb(id varchar(20),name varchar(10))

create clustered index idx_clu_tb on tb(id)
go

create trigger tri_tb on tb
INSTEAD OF INSERT
as
begin
set nocount on
declare @i int,@id varchar(20),@j int
select @i=count(*) from inserted
begin tran
if exists(select 1 from num_tb where convert(char(8),d,112)=convert(char(8),getdate(),112))
begin
select @j=id from num_tb with(TABLOCKX)
update num_tb with(TABLOCKX) set id=id+@i
end
else
begin
update num_tb with(TABLOCKX) set d=getdate(),id=@i
set @j=0
end
commit tran
select * into #t from inserted
update #t set id=convert(varchar(8),getdate(),112)+right('00000'+rtrim(@j),5),@j=@j+1
insert tb select * from #t
end
go

alter trigger tri_tb on tb
INSTEAD OF INSERT
as
begin
set nocount on
declare @i int,@id varchar(20),@j int
select @i=count(*) from inserted
begin tran
update num_tb with(TABLOCKX) set
id=(case when convert(char(8),d,112)=convert(char(8),getdate(),112)
        then id+@i else @i end),
@j=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) then id else 0 end),
d=getdate()
commit tran
select * into #t from inserted
update #t set id=convert(varchar(8),getdate(),112)+right('00000'+rtrim(@j),5),@j=@j+1
insert tb select * from #t
end
go
--创建表

go     


--插入记录测试
declare @i int
set @i=0
while @i<=10000
begin
insert into tb(name) values('张三')
insert into tb(name) select '张四'
union all select '张五'
union all select '张六'
union all select '张七'
union all select '张八'
union all select '张九'
union all select '张十'
set @i=@i+1
end

 

 

go
--删除环境
drop table tb

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值