您的位置:首页 > 其它

触发器 实现 自动编号

2009-03-29 10:10 190 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: