触发器 实现 自动编号

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER TRIGGER [Trigger_Insert]
   ON  [dbo].[表名]
   After INSERT
AS
BEGIN
    declare @id int,@pid varchar(16),@temppid varchar(16)
    --从Inserted表中取得主键的自动编号
    select @id=ID from Inserted
    --获取当前日期格式为"TJT20081010"
    select @pid = 'TJT' + Convert(varchar(8),GetDate(),112);
    --获取最后一个PID
    select top 1 @temppid=编号 from 表 where 编号 like @pid+'%' order by ID desc
    if (@temppid is null)
        begin
            --如果今天没有插入过数据,则初始值为'TJT200810100001'
            set @pid = @pid + '0001'
        end
    else
        begin
            --否则从最后一个日期取得编号,并末尾加上1,组成新编号
            set @pid = @pid + right(cast(power(10,4) as varchar)+(convert(int,substring(@temppid,12,4))+1),4)
        end

    --更新编号
     update 表 set  编号 =@pid where ID = @id
END

原文地址:https://www.cnblogs.com/xianzuoqiaoqi/p/1424293.html