数据库生成流水号

1.在触发器里编辑,选择所需要的字段

2.定义流水号格式内容

BEGIN 
	SET NOCOUNT ON
    --@table_id:刚刚插入数据库的最新记录的ID,@table_stream:表中的流水号日期部分,@last_stream:表中的最后一个流水号
    declare @table_id int,@table_stream varchar(15),@last_stream varchar(15) 
    --因为是在insert之后,所以找到表里最新的ID
    select top 1 @table_id=id from 表名 ORDER BY id desc
    --获取当前日期格式为"yyyyMMdd" 
    select @table_stream = Convert(varchar(8),GetDate(),112); 
    --获取最后一个流水号
    select top 1 @last_stream=表字段 from 表名 where 表字段 like @table_stream+'%' order by id desc 
    if (@last_stream is null) 
        begin 
            --如果今天没有插入过数据,则初始值为'20230530001' 
            set @table_stream = @table_stream + '001' 
        end 
    else 
        begin 
            --否则从最后一个日期取得编号,并末尾加上1,组成新编号 
						--power(10,3)是拼一个1000,如果流水号是日期+四位数,就是power(10,4):10000
						--substring('202305300001',9,3),从第9位截取取3个,即001
						--right(XXX,3)补齐00X
            set @table_stream = @table_stream + right(cast(power(10,3) as varchar)+(convert(int,substring(@last_stream,9,3))+1),3) 
        end
    --更新编号 
    update 表名 set 表字段=@table_stream where id = @table_id
END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值